【发布时间】:2012-11-02 12:49:23
【问题描述】:
我想确认在以下情况下会发生的行为。假设我有一些函数定义为:
std::vector<Object*> FuncA()
Result FuncB()
其中 result 是一个带有构造函数的类
Result(const std::vector<Object*>& result)
{
this->result = result;
}
现在,FuncB 执行以下操作:
Result FuncB() {
... some stuff here ...
return Result(FuncA())
}
FuncA 返回的向量何时会被销毁(调用其析构函数)?当结果超出范围时会是这样吗?持有对它的引用的结果是否会延长其生命周期?如果不能,您能否解释一下原因以及实现我所追求的方法?
谢谢
编辑:这是结果类
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);
};
【问题讨论】:
-
请贴出
Result的定义。答案取决于里面存储的内容。 -
不要使用指针向量,这很容易造成内存泄漏。如果你不想要
std::vector<Object>,至少使用std::vector<std::shared_ptr<Object>>。