Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using move semantics for a cast operator

Tags:

c++

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?

like image 692
P45 Imminent Avatar asked Jul 01 '15 11:07

P45 Imminent


People also ask

What is the use of move semantics?

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.

How are Move semantics implemented?

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.

How do you write a move assignment operator?

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.

Should you 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).


2 Answers

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]

like image 70
Angew is no longer proud of SO Avatar answered Nov 07 '22 14:11

Angew is no longer proud of SO


Yes, you can using r-value this syntax:

operator bar() &&{ /* std::move(...); */ }
like image 23
p2rkw Avatar answered Nov 07 '22 12:11

p2rkw