我有一个方法,有一些指针作为参数.可以使用来自被调用者的命名指针调用此方法,也可以动态创建指向新对象的指针,并在调用方法时将其作为参数直接传递.
myClass *myPtr = new myClass(...);
myMethod(myPtr);
Run Code Online (Sandbox Code Playgroud)
VERUS
myMethod(new myClass(...));
Run Code Online (Sandbox Code Playgroud)
问题是,如果这两个都是有效选项,那么如何正确释放传入的指针?如果在程序中再次访问myPtr,则删除myMethod中的myPtr将导致崩溃.如果我不删除myPtr,第二个选项将导致内存泄漏(如果使用它).使用这两个选项都有好处,所以两者都不应该破坏程序.
除了使用STL之外,这个问题有哪些解决方案?我是否必须实施自己的垃圾收集器?
我会说,在这种情况下,调用者应该负责释放对象.您可以考虑各种选项,最简单的是:
myClass myInstance = myClass; // or myClass(arg1, arg2, ...)
// and the pass it to your method like this:
myMethod(&myInstance);
Run Code Online (Sandbox Code Playgroud)
您还可以考虑一些智能指针选项std::tr1::shared_ptr或类似于boost的东西.
更新:如果您的方法应该能够将NULL-pointer作为其参数,那么根本没有问题:
// this is your method declaration:
void myMethod(const myClass *myPtr);
// in your tests or wherever in your code you can call it like
myClass myInstance = myClass; // or myClass(arg1, arg2, ...)
myMethod(&myInstance);
// or like this:
myMethod(NULL);
// for as long as your method has something like this in it:
if (myPtr)
myPtr->someMethod();
Run Code Online (Sandbox Code Playgroud)