lundi 3 avril 2017

Is it fine to use variables after they being used as arguments of emplace_back?

Probably, a lame question, but I keep failing to find comprehensive answer.

Parameters of std::vector::emplace_back are r-value references. As far as I understand, it is unsafe to use object after it was passed somewhere by r-value reference. I mean following:

std::string str("hello world");
std::string str2(std::move(str)); // string::string(string &&);
cout << str;                      // unsafe, str was moved to str2

So, what will happen in following example?

std::vector<std::string> array;
std::string str("hello world");   // what if add 'const' qualifier here?
array.emplace_back(str);          // template <class... Args>
                                  // void emplace_back (Args&&... args);
std::cout << str;                 // safe or not? str was moved or copied?

I'm really confused here. My tests shows that,str is safe to use after emplace_back, but my (broken?) logic tells me that str was moved and shouldn't be used after that.

PS. Sorry for my bad English :)

Aucun commentaire:

Enregistrer un commentaire