gpt4 book ai didi

c++ - shared_ptr 魔法 :)

转载 作者:IT老高 更新时间:2023-10-28 12:03:25 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/3899790/

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