Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move semantics for a conversion operator

What's the syntax for a movable conversion operator?

I have a wrapper that wraps around obj, which has an obj conversion operator:

class wrap {
public:
   operator obj() { ... }
private:
   obj data_;
};

How can I find out whether data_ should be copied or moved?

like image 807
Candy Chiu Avatar asked May 25 '12 17:05

Candy Chiu


People also ask

What is a conversion operator?

A conversion operator, in C#, is an operator that is used to declare a conversion on a user-defined type so that an object of that type can be converted to or from another user-defined type or basic type. The two different types of user-defined conversions include implicit and explicit conversions.

What is Move semantics in C++?

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 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.

What is a conversion operator in CPP?

Conversion Operators in C++ C++ supports object oriented design. So we can create classes of some real world objects as concrete types. Sometimes we need to convert some concrete type objects to some other type objects or some primitive datatypes. To make this conversion we can use conversion operator.


1 Answers

The syntax for that would be something like this:

class wrap {
public:
   operator obj() const & { ... }   //Copy from me.
   operator obj() && { ... }  //Move from me.
private:
   obj data_;
};

The first version will be called when the second version cannot be called (ie: the wrap instance being converted is not a temporary or there is no explicit use of std::move).

Note that Visual Studio didn't implement this aspect of r-value references in VS11.

like image 59
Nicol Bolas Avatar answered Nov 13 '22 11:11

Nicol Bolas