dimanche 8 mars 2015

How std::move applied on function return value?

On testing the below code snippet, here i am taking one string vector and trying to return it with std::move(vector). If i am using member function signature like this std::vector<std::string>&& getVector() then its working fine. If i am using this std::vector<std::string>& getVector() then its not moving/clearing the vector contents.


Please let me know the correct move semantics to be followed. And please explain difference between both code.


Code :



#include <iostream>
#include <vector>
#include <string>

class VectorMoveDemo
{
public:
void add(std::string item)
{
results_.push_back(item);
}
std::vector<std::string>& getVector()
{
return std::move(results_);
}
private:
std::vector<std::string> results_;
};

int main()
{
VectorMoveDemo v;
v.add("Hello ");

std::cout << "First Time : " << "\n";
std::vector<std::string> temp = v.getVector();
for(auto &item : temp)
{
std::cout << item << "\n";
}
std::cout << "Second Time : " << "\n";

v.add("World");

std::vector<std::string> temp2 = v.getVector();
for(auto &item : temp2)
{
std::cout << item << "\n";
}
}


First:



std::vector<std::string>& getVector()
{
return std::move(results_);
}


output :



First Time :
Hello
Second Time :
Hello
World


Second



std::vector<std::string>&& getVector()
{
return std::move(results_);
}


output :



First Time :
Hello
Second Time :
Hello
World


Any help would be really appreciated.


Aucun commentaire:

Enregistrer un commentaire