Reputation: 16703
I am wondering if the following is a safe way of returning a deep vector
of objects.
class MyClass {
//...
}
std::vector<MyClass> get_list(a,b,c) {
// obj is created on the stack
MyClass obj(a,b,c);
std::vector<MyClass> objects();
objects.push_back(obj);
// objects[0] contains a pointer to a stack variable?
return objects
}
In particular, how does the returned vector not contain a reference to a stack memory location?
Upvotes: 0
Views: 239
Reputation: 103693
Whether it's safe or not depends upon MyClass
. But assuming it's a well behaved class with value semantics, then yes, it's perfectly safe. std::vector
stores its objects by value. When you do this:
objects.push_back(obj);
A copy of obj
is put into the vector (assuming you actually had a vector, which you don't). And when you return the vector it is moved (though this move can be and usually is optimized away) out to the calling function.
Upvotes: 3
Reputation: 22886
NO.
objects.push_back(obj);
The local variable, i.e. obj, is COPIED into the vector. So the vector won't contain a reference to a local variable.
By the way, you CANNOT define a vector like this:
std::vector<MyClass> objects();
In fact, this is a function declaration: a function named objects, which has no parameter, and returns a std::vector.
Instead, you should do it like this:
std::vector<MyClass> objects;
Upvotes: 2
Reputation: 1527
In this situation, objects.push_back(obj);
calls the T const&
version of std::vector::push_back which will copy the parameter.
Upvotes: 0