Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explicit move constructor needed in container?

Tags:

c++

c++11

I have a templated container class:

 template<class Stuff>
 class Bag{
     private:
        std::vector<Stuff> mData;
 };

I want to do

  void InPlace(Bag<Array>& Left){
      Bag<Array> temp;
      Transform(Left, temp); //fills temp with desirable output
      Left = std::move(temp);
  }

Suppose Array has user-defined move semantics, but Bag does not. Would mData in this case be moved or copied?

like image 612
AGML Avatar asked Jun 15 '17 17:06

AGML


People also ask

Can a class have multiple move constructors?

there is no user-declared destructor . then the compiler will declare a move constructor as a non- explicit inline public member of its class with the signature T::T (T&&). A class can have multiple move constructors, e.g. both T::T(const T&&) and T::T(T&&).

Does making a constructor explicit prevent all types of conversions?

However, note that making a constructor explicit only prevents implicit conversions. Explicit conversions (via casting) are still allowed: Direct or uniform initialization will also still convert parameters to match (uniform initialization will not do narrowing conversions, but it will happily do other types of conversions).

What is trivial move constructor in C?

Trivial move constructor. A trivial move constructor is a constructor that performs the same action as the trivial copy constructor, that is, makes a copy of the object representation as if by std::memmove. All data types compatible with the C language (POD types) are trivially movable.

What is an implicit conversion operator in C++?

By default, C++ will treat any constructor as an implicit conversion operator. Consider the following case: Although function printFraction () is expecting a Fraction, we’ve given it the integer literal 6 instead.


1 Answers

It would be moved, not copied.

I would suggest looking at the following image:


enter image description here


This clearly shows that the compiler implicitly generates a move constructor as long as the user doesn't define his/her own :

  • destructor
  • copy constructor
  • copy assignment
  • move assignment

Since your class has none of these user defined constructors the compiler generated move constructor will be called, that constructor will move mData.

like image 161
Hatted Rooster Avatar answered Oct 25 '22 22:10

Hatted Rooster