C ++ What is the best way to transfer data from a class member (std :: move)

Imagine that I have a class whose main task is to populate a data container. I would like to move data from this class. Therefore, I have:

class cCreator { public: void generate() { ///generate the content of data_ and populate it .... .... } //variation 1 std::vector<int>&& getData1() { return std::move(data_); } //variation 2 std::vector<int> getData2() { return std::move(data_); } private: std::vector<int> data_ }; 

S what is the difference between option 1 and option 2 getData (). What changes when I omit && from function definition

+6
source share
3 answers

In the first case, no movement occurs in the function itself. You simply return the rvalue link, which allows the original caller to navigate if necessary. In the second case, the data is actually moved to temporary, regardless of how the caller uses the result.

 cCreator c1, c2; c1.getData1(); // no move std::vector<int> v1 = c1.getData1(); // move directly from data_ // into v1. c2.getData2(); // move to temporary, which isn't used. std::vector<int> v2 = c2.getData1(); // move from data_ to temporary, // then move from temporary to v2. 
+3
source

Version 1 is probably a bad idea, things like f(x.getData()) may or may not move, depending on f signature. In general, we want any move be explicit in the code, so you should have at least:

 std::vector<int>&& getData() && { return std::move(data_); } 

So now the movement should be explicit: f( std::move(x).getData() ) , and you probably want to provide overload for const & just for observation.

Version 2 will be approved if it has a different name. In my experience, 99% of people perceive getX as an operation without modification. Better name it releaseData , which is consistent with the name unique_ptr::release .

+1
source

I assume that in this particular case, when the container whose data is being retrieved (moved) is an stl vector, std :: swap would be a valid option. Just put:

 const std::vector<int>& getData() const; std::vector<int>& getData(); 

woudl allows the user to safely retrieve data if he so desires. This can only be a viable option if C ++ 11 is unavailable for any reason.

+1
source

All Articles