在C++中有很多方法可以做到这一点.不幸的是,大多数都会导致混淆谁负责分配和解除分配对象.我推荐两种方法:
// Return a real object, automatic stack allocation.
Foo GetFoo1()
{
Foo f;
// Init f.
return f;
}
// Use a smart, reference counted pointer that handles deallocation itself.
boost::shared_ptr<Foo> GetFoo2()
{
boost::shared_ptr<Foo> f(new Foo);
// Init f
return f;
}
Run Code Online (Sandbox Code Playgroud)
答案取决于您正在做什么以及谁负责解除分配.
第一种方法:在堆上分配并返回.谁曾调用该函数将负责删除返回的指针.
SomeObject* constructObject ()
{
SomeObject* obj = new SomeObject ();
return obj;
}
Run Code Online (Sandbox Code Playgroud)
然后在其他一些功能
void functionThatNeedsObject ()
{
SomeObject* obj = constructObject ();
//You must delete obj when done
}
Run Code Online (Sandbox Code Playgroud)
第二种方法:返回参考.您必须注意不要通过返回本地或临时变量超出范围.
不要这样做:
int& DoubleValue(int nX)
{
int nValue = nX * 2;
return nValue; // return a reference to nValue here
} // nValue goes out of scope here
Run Code Online (Sandbox Code Playgroud)
您可以返回对成员变量的引用或作为参数传递给函数的变量.
SomeStruct& RefFunction(SomeStruct& nX, SomeStruct& nY)
{
return nX;
} //nX is still in scope because it was passed to us
Run Code Online (Sandbox Code Playgroud)
要么按值返回(人们错误地认为这很慢),或者,如果要返回多态类型的覆盖,则返回auto_ptr(或更好的C++ 0x中的unique_ptr).
你不使用shared_ptr的原因是你永远不能从指针中取出指针并使用不同的所有权语义.
永远不要返回对本地实例的引用.