Why is there different elision behaviour between static_cast<T&&> and move<T> in VS 2017
Asked Answered
C

0

7

I am struggling to understand the different behavior shown between move and an rvalue cast

given:

template <class T> void f1(T param) {  }

struct B { B() = default;  B(B&&) { cout << "Move constructor\n"; } };
void demo()
{

    f1(static_cast<B&&>(B())); // does not call move constructor - constructor is elided
    f1(move(B())); // calls move constructor - no elision
}

The move call forces the call to the move constructor, while the static cast does not, and the constructor is apparently elided. This seems strange as the definition of std::move looks very much like a static cast.

Why the different behavior?

Update: Cannot be reproduced with gcc. Behavior shown only with MSVC

Corposant answered 5/10, 2020 at 10:0 Comment(10)
move<B> - The explicit argument is kinda idiosyncratic, just saying. It's meant to be about deducing the argumentsPerpetrate
what are your observations? What makes you think that move constructor is not called in one case? Cannot reproduce: godbolt.org/z/h5WvEdRidgepole
please provide a minimal reproducible exampleRidgepole
@idclev463035818 Only one print statement produced on VS 2017, debug mode, x64Corposant
@GonenI if you look at the CE link by idclev, you can see that no move constructors are being called, everything is optimized out and only two simple couts are happening.Tilghman
@Tilghman - You are misrepresenting the assembly and output. Those are empty objects with a user-defined move constructor. The objects may be optimized out, but the behavior is as-if they were move constructed. The OP is saying that they managed to observe only a single output. That's the wrong behavior.Perpetrate
@StoryTeller-UnslanderMonica Yes right. And In debug mode, the same behaviour is observable. However MSVC does indeed call move constructor on one and not the other if I see it correctly.Tilghman
@idclev463035818 You cannot reproduce with GCC. With MSVC, there is a difference: godbolt.org/z/ccG9ra.Sibie
@DanielLangr indeed. I also managed to get no output at all with MSVC, unfortunately I don't remember how and lost the linkRidgepole
Possibly wrong copy elision on msvc part.Epilogue

© 2022 - 2024 — McMap. All rights reserved.