Suppose I have two classes foo
, and bar
that are fairly well-related, by which I mean that they contain common data members.
I have a cast operator operator bar() const;
in the foo
class.
I also have a function func
that takes a bar
.
If I call func
with an anonymous temporary foo
then the cast operator will be called. But as I don't need the foo
, can I declare some sort of move cast so explicitly optimising out any unnecessary copies?
Move semantics allows you to avoid unnecessary copies when working with temporary objects that are about to evaporate, and whose resources can safely be taken from that temporary object and used by another.
Move semantics was introduced in the C++11 standard. To implement it, rvalue references, move constructors, and the move assignment operator were added. Also, some functions were added to the standard template library (STL) to support move semantics. For example, std::move and std::forward.
To create a move assignment operator for a C++ class In the move assignment operator, add a conditional statement that performs no operation if you try to assign the object to itself. In the conditional statement, free any resources (such as memory) from the object that is being assigned to.
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).
If your compiler supports ref-qualifiers on member functions (a C++11 feature), you can:
operator bar() const &
{
return bar(the_common_data);
}
operator bar() &&
{
return bar(std::move(the_common_data));
}
[Live example]
Yes, you can using r-value this
syntax:
operator bar() &&{ /* std::move(...); */ }
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