gpt4 book ai didi

c++ - 关于 Safe 类是异常安全的声明的澄清

转载 作者:太空宇宙 更新时间:2023-11-03 10:32:05 25 4
gpt4 key购买 nike

您会在 this document 的第 937 页找到以下代码:

template<class T> class Safe
{
T* p; // p points to a T allocated using new
public:
Safe() : p(new T) {}
~Safe() { delete p; }
Safe& operator=(const Safe& a) { *p = *a.p; return *this; }
// ...
};

看来,p指向的对象会在上面的赋值运算符中泄露。

最佳答案

这不是泄漏,因为他没有更改指针。如果他这样做了

Safe& operator=(const Safe& a) { p = a.p; return *this; }

那么就是内存泄漏了。他正在对 p 指向的对象进行赋值,而不是 p 本身。

关于c++ - 关于 Safe 类是异常安全的声明的澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14025642/

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