If I have a struct in which I did not provide any copy and move constructor:
struct MyStruct {
MyStruct() { // this is the only function
...
}
...
};
then if I do the following:
std::vector<MyStruct> vec;
...
vec.push_back(MyStruct());
instead of using std::move() like the followings:
vec.push_back(std::move(MyStruct()));
Will c++11 smartly do the move for my temporary variable? Or, how can I make sure it is a move instead of a copy?
In C++11 std::vector::push_back will use a move constructor if passed an rvalue (and a move constructor exists for the type), but you should also consider using std::vector::emplace_back in such situations; std::vector::emplace_back will construct the object in place rather than moving it.
Will c++11 smartly do the move for my temporary variable? Or, how can I make sure it is a move instead of a copy?
It depends. This
vec.push_back(MyStruct());
will bind to
std::vector<MyStruct>::push_back(MyStruct&&);
but whether the rvalue passed is moved or copied depends fully on whether MyStruct has a move copy constructor (likewise for move assignment).
It will make absolutely no difference if you call
vec.push_back(std::move(MyStruct()));
because MyStruct() is already an rvalue.
So it really depends on the details of MyStruct. There is simply not enough information in your question to know if your class has move constructor.
These are the conditions that must be met for a class to have an implicitly generated move constructor:
Of course, you can always provide your own if any of these conditions are not met:
MyStruct(MyStruct&&) = default;
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