I have code like this:
#include <iostream>
#include <exception>
#include <stdexcept>
#include <string>
#include <vector>
#include <utility>
struct Foo {
Foo(std::string t):text(t){}
//destructor deleted
std::string text;
};
int main()
{
std::vector<Foo> v;
v.push_back(Foo("foo 1"));
v.push_back(Foo("foo 2"));
v.push_back(Foo("foo 3"));
for(auto& foo : v){
std::cout<<foo.text<<"\n";
}
Foo fooBack = std::move(v.back());
std::cout<<fooBack.text<<"\n";
for(auto& foo : v){
std::cout<<foo.text<<"\n";
}
}
std::move() in this case doesn't steal the return variable. Is there a way to avoid the excess copy?
This is the result:
foo 1 foo 2 foo 3 foo 3 foo 1 foo 2 foo 3
new code based on sugestions(dont know if keep asking on same thread dont know if that was what i expected , the reaon i was doind all this move is to reduce code):
#include <iostream>
#include <exception>
#include <stdexcept>
#include<string>
#include<vector>
#include<utility>
struct Foo {
Foo(std::string t):text(t){
std::cout<<text<<" construct foo called \n";
}
Foo(const Foo& f){
text = f.text;
std::cout<<text<<"copy construct foo called \n";
}
Foo(Foo&& f){
text = std::move(f.text);
std::cout<<text<<"move construct foo called \n";
}
/*
~Foo() {
}
*/
std::string text;
};
int main()
{
std::vector<Foo> v;
v.emplace_back("foo 1");
v.emplace_back("foo 2");
v.emplace_back("foo 3");
for(auto&& foo : v){
std::cout<<foo.text<<"\n";
}
Foo fooBack = std::move(v.back());
v.pop_back();
std::cout<<fooBack.text<<"\n";
for(auto&& foo : v){
std::cout<<foo.text<<"\n";
}
}
new results to see it in action
foo 1 construct foo called foo 2 construct foo called foo 1copy construct foo called foo 3 construct foo called foo 1copy construct foo called foo 2copy construct foo called foo 1 foo 2 foo 3 foo 3move construct foo called foo 3 foo 1 foo 2
std::moveit doesn't move anything. All it does is perform a cast.std::move()itself is just a type-cast to an rvalue reference, it doesn't steal anything on its own. It is actually the job of move constructors and move assignment operators that take rvalue references as input to do the actual stealing.Fooobject'stextremains unchanged after being moved from due to short string optimization. The state of astd::stringis undefined after being moved from; it is not guaranteed to be empty.