Discussion: Will It Move?
Execute the code to understand the output and gain insights into move constructors.
Run the code
Now, it’s time to execute the code and observe the output.
C++
#include <iostream>struct Member{};struct WillItMove{WillItMove() = default;WillItMove(WillItMove &&) = default;const Member constMember_{};};int main(){WillItMove objectWithConstMember;WillItMove moved{std::move(objectWithConstMember)};std::cout << "It moved!\n";}
The WillItMove has a const member. We can’t move from a const object, so why could we still move from objectWithConstMember?
Understanding the output
In this puzzle, we first initialize WillItMove objectWithConstMember;. Then, on line 17, we initialize a new WillItMove moved{std::move(objectWithConstMember)};. Since WillItMove has no copy constructor, the only alternative to initialize moved is the move constructor. But how can the move constructor perform a move operation from the const Member constMember?
The move constructor
Let’s start digging from the outside in.
First, what does std::move(objectWithConstMember) do? The ...
Ask