gpt4 book ai didi

c++ - shared_ptr 魔法 :)

转载 作者:可可西里 更新时间:2023-11-01 17:59:56 26 4
gpt4 key购买 nike

Mr. Lidström and I had an argument :)

先生。 Lidström 的声明是一个构造 shared_ptr<Base> p(new Derived);不要求 Base 具有虚拟析构函数:

Armen Tsirunyan: "Really? Will the shared_ptr clean up correctly? Could you please in this case demonstrate how that effect could be implemented?"

Daniel Lidström: "The shared_ptr uses its own destructor to delete the Concrete instance. This is known as RAII within the C++ community. My advice is that you learn all you can about RAII. It will make your C++ coding so much easier when you use RAII in all situations."

Armen Tsirunyan: "I know about RAII, and I also know that eventually the shared_ptr destructor may delete the stored px when pn reaches 0. But if px had static type pointer to Base and dynamic type pointer to Derived, then unless Base has a virtual destructor, this will result in undefined behavior. Correct me if I am wrong."

Daniel Lidström: "The shared_ptr knows the static type is Concrete. It knows this since I passed it in its constructor! Seems a bit like magic, but I can assure you it is by design and extremely nice."

所以,判断我们。在不要求多态类具有虚拟析构函数的情况下,如何实现(如果是)shared_ptr?提前致谢

最佳答案

是的,可以通过这种方式实现 shared_ptr。 Boost 确实如此,C++11 标准也需要这种行为。作为一种额外的灵 active ,shared_ptr 管理的不仅仅是一个引用计数器。所谓的删除器通常被放入同样包含引用计数器的内存块中。但有趣的是这个删除器的类型不是 shared_ptr 类型的一部分。这称为“类型删除”,基本上与用于实现“多态函数”boost::functionstd::function 以隐藏实际仿函数类型的技术相同.为了使您的示例工作,我们需要一个模板化的构造函数:

template<class T>
class shared_ptr
{
public:
...
template<class Y>
explicit shared_ptr(Y* p);
...
};

因此,如果您将它与您的类 BaseDerived 一起使用 ...

class Base {};
class Derived : public Base {};

int main() {
shared_ptr<Base> sp (new Derived);
}

...带有Y=Derived 的模板化构造函数用于构造shared_ptr 对象。因此,构造函数有机会创建适当的删除器对象和引用计数器,并将指向此控制 block 的指针存储为数据成员。如果引用计数器达到零,将使用先前创建的和 Derived 感知的删除器来处理该对象。

C++11 标准对此构造函数 (20.7.2.2.1) 有以下说明:

Requires: p must be convertible to T*. Y shall be a complete type. The expression delete p shall be well formed, shall have well defined behaviour and shall not throw exceptions.

Effects: Constructs a shared_ptr object that owns the pointer p.

对于析构函数 (20.7.2.2.2):

Effects: If *this is empty or shares ownership with another shared_ptr instance (use_count() > 1), there are no side effects.Otherwise, if *this owns an object p and a deleter d, d(p) is called.Otherwise, if *this owns a pointer p, and delete p is called.

(强调使用粗体是我的)。

关于c++ - shared_ptr 魔法 :),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47746238/

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