In this code, a huge vector could be (depending on compiler) copied upon return:
vector<string> foo() {
vector<string> vec;
//make vec huge
return vec;
}
vector<string> bar = foo();
How do I avoid copying the vector, without relying on compiler optimizations?
Now, understand that this is just a simple example, with a single return statement. But for more complex cases, it is a possibility that even good compilers will not be able to do optimizations to avoid copying the vector. (This answer to another question mentions one such case.)
(Relying on compiler optimizations always seemed rather strange to me in the first place, since I'm supposed to be writing good, portable, C++ code, as opposed to worrying about how this and that compiler does things under the hood. All those "compiler optimization" answers to the other questions therefore puzzle me.)
One idea I came up with so far is to use C++11's smart pointers:
shared_ptr<vector<string>> foo() {
shared_ptr<vector<string>> vec_ptr = make_shared<vector<string>>();
//make *vec_ptr (i.e. the actual vector) huge
return vec_ptr;
}
shared_ptr<vector<string>> bar_ptr = foo();
//now, *bar_ptr is the underlying vector we can use
It looks like this will avoid the copy in all cases. The problem is that this code is getting to be quite cumbersome.
Any good non-cumbersome alternatives? Supposedly, C++11 provides some new "move" functionality through rvalue references. Could those help?