gpt4 book ai didi

c++ - 如果内存未被其他任何引用,则释放指针

转载 作者:太空狗 更新时间:2023-10-29 23:26:04 24 4
gpt4 key购买 nike

我有一个方法,它有几个指针作为参数。可以使用来自被调用方的命名指针调用此方法,也可以动态创建指向新对象的指针并在调用方法时将其作为参数直接传递。

myClass *myPtr = new myClass(...);
myMethod(myPtr);

维鲁斯

myMethod(new myClass(...));

问题是,如果这两个都是有效选项,如何正确释放传入的指针?如果在程序中再次访问 myPtr,则在 myMethod 中删除 myPtr 将导致崩溃。如果我不删除myPtr,第二个选项如果使用的话会导致内存泄漏。使用这两个选项各有好处,因此两者都不应破坏程序。

除了使用STL,这个问题还有哪些解决方案?我是否必须实现自己的垃圾收集器?

最佳答案

我会说,在这种情况下,调用者 应该负责释放对象。您可以考虑多种选择,最简单的是:

myClass myInstance = myClass;  // or myClass(arg1, arg2, ...)
// and the pass it to your method like this:
myMethod(&myInstance);

您还可以考虑一些智能指针选项,例如 std::tr1::shared_ptr 或来自 boost 的东西。

更新:如果您的方法应该能够获取 NULL 指针作为其参数,则完全没有问题:

// 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();

关于c++ - 如果内存未被其他任何引用,则释放指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2057047/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com