c++ - C++ Primer 第 5 版中发现的错误 shared_ptr<int>

标签 c++ c++11 c++14 shared-ptr errata

您好,我正在阅读 C++ primer 第 5 版,我想我在 shared_ptr 部分下发现了一个错误。首先,我正在编写代码和他们给出的解释。然后我会写下我认为的错误和我认为实际发生的事情。代码如下:

shared_ptr<int> p(new int(42));// reference count is 1
int *q = p.get();// ok: but don't use q in any way that might delete its pointer
{//new block started
    shared_ptr<int>(q);
}// block ends, q is destroyed, and the memory to which q points is freed
int foo = *p;// undefined; the memory to which p points was freed

他们给出的解释如下:

In this case, both p and q point to the same memory. Because they were created independently from each other, each has a reference count of 1. When the block in which q was defined ends, q is destroyed. Destroying q frees the memory to which q points. That makes p into a dangling pointer, meaning that what happens when we attempt to use p is undefined. Moreover, when p is destroyed, the pointer to that memory will be deleted a second time.

现在我认为错误是语句“当定义 q 的 block 结束时,q 被销毁。销毁 q 释放 q 指向的内存。”以及他们给出的推理为什么 p 是一个悬挂指针的背后是错误的。以下是我为什么 p 是悬空指针以及为什么第一个引用的语句是错误的原因。

  1. 当定义 q 的 block 结束时,q 被销毁。但是 q 指向的内存不会被释放,因为 q 是一个内置指针而不是 shared_ptr。除非我们显式地写 delete q,否则相应的内存将不会被释放。
  2. 现在,在新 block 中,我们使用 q 创建了一个临时的 shared_ptr。但是这个临时文件是独立于 p 的。因此,当这个内部 block 结束时,临时文件被销毁,因此内存被释放。但请注意,p 仍指向已释放的相同内存。所以 p 现在是一个悬空指针,在语句 int foo=*p 中使用 p 是未定义的。

我认为这是对为什么 p 是悬挂指针的正确解释,也是应该存在的更正。有人可以确认这是正确的还是我做错了什么?

最佳答案

正如您正确指出的那样,文本描述和代码中的注释都不符合代码。它们更符合这样的代码:

shared_ptr<int> p(new int(42));// reference count is 1
{//new block started
    shared_ptr<int> q(p.get());
}// block ends, q is destroyed, and the memory to which q points is freed
int foo = *p;// undefined; the memory to which p points was freed

如果我猜的话,我会说这个例子最初是这样的,然后有人决定引入原始指针,但没有意识到它也需要更改注释和文本。

关于c++ - C++ Primer 第 5 版中发现的错误 shared_ptr<int>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66515465/

相关文章:

c++ - 除了 Corba 组件之外,是否存在任何 C++ 组件框架?

c++ - 默认的 STL 分配器如何分配?

C++ 基于其他 int 数组排序

c++ - 使用 C++14 的具有多个返回类型的 decltype(auto)

c++ - 在数组末尾添加一个字符串?

c++ - 右值引用的生命周期

c++ - 使用 Cereal 库序列化 Eigen::Matrix

c++ - random_shuffle 修改打乱后的对象 (c++11)

c++ - struct::type+using 和 just using 之间的区别?

c++ - 如何确定一个模板参数可以转换成算术类型?