Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are member variables in temporary objects implicitly moved when possible?

In my classes I use std::vector etc. as member variables, which come with their own move constructors. I don't explicitly declare move constructors for my classes and they are not implicitly declared for the most part.

If the implicit copy constructor or the implicit assignment operator of my class is called with an rvalue, are the members that have move constructors copied or moved?

If they are moved, is there any reason for trying to avoid temporaries when using classes with move constructible members?

like image 540
gokturk Avatar asked May 17 '13 14:05

gokturk


People also ask

Should I always use std move?

Q: When should it be used? A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

Are move constructor automatically generated?

If a copy constructor, copy-assignment operator, move constructor, move-assignment operator, or destructor is explicitly declared, then: No move constructor is automatically generated. No move-assignment operator is automatically generated.

What does the default move constructor do?

A move constructor enables the resources owned by an rvalue object to be moved into an lvalue without copying. For more information about move semantics, see Rvalue Reference Declarator: &&.

How to define move constructor?

A move constructor allows the resources owned by an rvalue object to be moved into an lvalue without creating its copy. An rvalue is an expression that does not have any memory address, and an lvalue is an expression with a memory address.


1 Answers

If your class does not explicitly declare a move constructor/assignment operator and they are not declared implicitly either, then the implicitly declared copy ctor/assignment-op will not move the members, but copy them.

They would be moved if move ctor/assignment-op were declared implicitly for your class. You say they are not - why is that? Do your classes have custom destructors? You should strive for a design where you don't need a custom dtor, copy/move ctor and copy/move assignment op - sometimes called the "Rule of zero."

If you do need a custom dtor, you should declare move ctor/assignment-op explicitly to use move semantics. If your compiler supports it, you can declare them as defaulted.

like image 81
Angew is no longer proud of SO Avatar answered Oct 26 '22 09:10

Angew is no longer proud of SO