gpt4 book ai didi

c++ - 使用自动指针有效地处理资源

转载 作者:搜寻专家 更新时间:2023-10-31 01:23:16 24 4
gpt4 key购买 nike

我有一个看起来像这样的代码:

class Parent
{
auto_ptr<Resource> ptr2Resc;
public: void parentMethod(int i )
{
SomeOtherClass someOthrPtr = new SomeOtherClass(ptr2Resc);
}
};

The ctor of SomeOtherClass:
SomeOtherClass(auto_ptr<Resource> ptrRes);

所以现在当我调用 parentMethod 时,auto_ptr 被交换并且 ptr2Resc 被取消分配。我的 C++ 代码不支持 TR1 或 Boost。那么在父类析构函数期间释放 ptr2Resc 的最佳方法是什么,而不是在它作为参数传递时。我可以将它作为对 auto_ptr 的引用传递给 SomeOtherClass ctor 吗?

谢谢

最佳答案

以下是 Josuttis 书中关于通过引用传递 auto_ptr 的引述:

You might think about passing auto_ptrs by reference instead. However, passing auto_ptrs by reference confuses the concept of ownership. A function that gets an auto_ptr by reference might or might not transfer ownership. Allowing an auto_ptr to pass by reference is very bad design and you should always avoid it

正如我在评论中所说,如果您不打算转让所有权,您可以简单地将 SomeClass 的构造函数更改为采用原始指针。

关于c++ - 使用自动指针有效地处理资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1747691/

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