Reputation: 21625
I was recently learning about rvalue refs and move semantics of C++11, and found out that they were really good for performance, as they avoid unnecessary copying. However, I can also see a positive side effect of move semantics, which is that it can reduce the need for manual memory management. To illustrate my point, let us take the following example.
std::string* getTheLongString()
{
return new std::string("A really long string...");
}
std::string *a = getTheLongString();
........
delete a;
You could avoid call to delete, by using unique_ptr
, but still that means that the programmer would have to take care of it. With std::string
using move semantics, you could write the same example as follows, without loosing any performance.
std::string getTheLongString()
{
return std::string("A realy long string...");
}
std::string a = getTheLongString();
So, what do you think. Does move semantics really make memory management easier in C++?
Upvotes: 0
Views: 266
Reputation: 21576
The lack of Move Semantics pre-C++11 or the paranoia of Return Value Optimization pre-C++17 have never been a good reason to use "dynamic storage duration" in place of "automatic storage duration".
Pre-C++11:
Compilers were doing Return Value Optimization. If you were paranoid about RVO not happening, one of the ugly hacks was "out" parameters
void getTheLongString(std::string& str){
....
str = "A realy long string...";
}
std::string a;
getTheLongString(a);
"Initializing" a
here requires "Two work". Default Construction and a Copy Assignment.
C++11 and C++14:
Compilers are still doing Return Value Optimization. You don't need to worry about it not happening, because worse case would be a Move Construction.
std::string getTheLongString(){
return std::string("A realy long string...");
}
std::string a{getTheLongString()};
"Initializing" a
here is at most one work.
C++17 and beyond.
Return Value Optimization (more formally "Copy Elision") is guranteed to take place in the particular definition of getTheLongString()
. So nothing to worry about.
Upvotes: 3