Reputation: 1365
I'm wanting to confirm the behaviour that will happen in the following situation. Suppose I have some functions defined as:
std::vector<Object*> FuncA()
Result FuncB()
Where result is a class with constructor
Result(const std::vector<Object*>& result)
{
this->result = result;
}
Now, FuncB does the following:
Result FuncB() {
... some stuff here ...
return Result(FuncA())
}
When will the vector returned by FuncA be destroyed (have its destructor called)? Will it be when Result goes out of scope? Does result holding a reference to it extend its lifetime? If not could you please explain why and maybe a way to achieve what I'm after?
Thanks
Edit: Here's the result class
class Result
{
private:
std::vector<Object*> result;
void SetData(const Result& other);
void Free();
// Constructs the result and takes ownership of the memory.
Result(const std::vector<Object*>& result);
Result();
public:
Result(const Result& other);
Result& operator=(const Result& rhs);
~Result();
const Object& operator [] (int index);
};
Upvotes: 1
Views: 441
Reputation: 56956
If Result
holds a reference, then you have a problem. The object returned by FuncA
will be destroyed before the Result
object is returned.
Now, Result
holds by value. This means that the return value of FuncA
will be copied in the constructor. The vector will be destroyed when the Result
object is.
If you want to avoid the copy, take the object by value in the constructor:
Result(std::vector<Object*> result)
: result(std::move(result))
{}
or, if you don't use C++11 (cf @Steve Jessop's comment)
Result(std::vector<Object*> result)
{
this->result.swap (result);
}
Upvotes: 2
Reputation: 258618
This is most likely the wrong way to go about doing what you want to do. The vector gets destroyed when Result
goes out of scope. The memory the pointers in the vector point to does not.
So you can return a vector and still use it, but if the pointers in a copy of that vector are freed, you'll run into UB.
Having a std::vector<std::shared_ptr<Object>>
instead will save you a lot of trouble.
Upvotes: 1