I want to implement move constructors (no copy constructor) for a certain type that needs to be a value type in a boost::unordered_map
. Let's call this type Composite
.
Composite
has the following signature:
struct Base
{
Base(..stuff, no default ctor) : initialization list {}
Base(Base&& other) : initialization list {}
}
struct Composite
{
Base member;
Composite(..stuff, no default ctor) : member(...) {}
Composite(Composite&& other) : member(other.member) {} // <---- I want to make sure this invokes the move ctor of Base
}
I want to write this so boost::unordered_map< Key , Composite >
does not require the copy constructor, and just uses the move constructor. If possible, I don't want to use the copy constructor of Base
in the initialization list of move constructor of Composite
.
Is this possible?
To create a move constructor for a C++ class. In the move constructor, assign the class data members from the source object to the object that is being constructed: _data = other._data; _length = other._length; Assign the data members of the source object to default values.
initialization: T a = std::move(b); or T a(std::move(b));, where b is of type T ; function return: return a; inside a function such as T f(), where a is of type T which has a move constructor. When the initializer is a prvalue, the move constructor call is often optimized out (until C++17)never made (since C++17), see copy elision .
A move constructor is eligible if it is not deleted. no move constructor with the same first parameter type is more constrained than it. Triviality of eligible move constructors determines whether the class is an implicit-lifetime type, and whether the class is a trivially copyable type .
2 Implementing an initializer-list constructor that doesn't copy the elements 1 using an initializer list where the values contain unique_ptr member variables 1 Initializing std::vector<std::thread> with initializer list
Say member(std::move(other.member))
.
As a golden rule, whenever you take something by rvalue reference, you need to use it inside std::move
, and whenever you take something by universal reference (i.e. deduced templated type with &&
), you need to use it inside std::forward
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With