Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move constructor and initialization list

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?

like image 801
lurscher Avatar asked Dec 10 '12 00:12

lurscher


People also ask

How to create a move constructor for a C++ class?

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.

How do you move in C++ with initializer and return?

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 .

When is a move constructor eligible in Java?

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 .

How to implement an initializer-list constructor that doesn't copy the elements?

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


1 Answers

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.

like image 106
Kerrek SB Avatar answered Oct 22 '22 11:10

Kerrek SB