43

I have a big class holding a lot of STL containers.
Will the compiler automatically make a move constructor that will move those containers to the target or I have to make my own?

0

2 Answers 2

68

A move constructor for a class X is implicitly declared as defaulted exactly when

  • X does not have a user-declared copy constructor,
  • X does not have a user-declared copy assignment operator,
  • X does not have a user-declared move assignment operator,
  • X does not have a user-declared destructor, and
  • the move constructor would not be implicitly defined as deleted.

So for example, if your class has a class type data member that does not have a move constructor, your class will not get a move constructor even if it doesn't have any copy/move constructor declared, because the implicitly declared move constructor would be defined as deleted (because of that data member).

Sign up to request clarification or add additional context in comments.

7 Comments

Interestingly, a user-declared move-constructor does not prevent the compiler from implicitly declaring a copy constructor. Maybe, that is worth mentioning here. At least this is what cprogramming.com/c++11/… says.
It's interesting that all members are required to have a move constructor. It seems sane to move all the members that can be moved and copy the ones that can't.
So the best shot is to define move ctor for yourself, don't rely on compiler.
@KevinCox It is common to guarantee that a move constructor does not throw an exception, while a copy constructor often can (e.g. out of memory), so this might not be a good idea. You could argue "that's ok, the implicit move constructor just wouldn't be noexcept" but I still think there's potential for surprise (i.e. bugs).
It's probably better to use explicitly defaulted move constructors: stackoverflow.com/questions/18290523/…
|
4

Default move constructors are generally tied to default copy constructors. You get one when you get the other. However, if you write a copy constructor/assignment operator, then no default copy and move constructors/assignment operators are written. If you write one of either set, you must write them all.

1 Comment

According to cppreference, an implicit copy constructor is provided even if you have an explicit move constructor by the user.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.