c++ - 广义复制构造函数

标签 c++ templates inheritance polymorphism

为什么像 shared_ptr 这样的类他们的构造函数中有另一个模板吗?

例如:

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

我一直在阅读 Scott Meyers 的Effective C++,第 45 条,其中说其背后的想法是通过它们使多态成为可能;即构造shared_ptr<A>来自 shared_ptr<B>如果 B 派生自 A。

但没有定义像

这样的构造函数
explicit shared_ptr(T * p);

够了吗?我的意思是,这段代码工作得很好:

class C1 {
};

class C2 : public C1 {
};

template<typename T>
class A
{
public:
  A(T &a)
  {
    var1 = a;
  }

  T var1;
};

int main(int argc, char *argv[])
{
  C2 c2;
  A<C1> inst1(c2);
}

那么为什么我们需要另一个构造函数模板呢?

最佳答案

如果没有模板构造函数,以下代码将具有未定义的行为:

#include <memory>

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

int main() {
    std::shared_ptr<Base> ptr( new Derived );
}

如果 shared_ptr 只需要一个 Base*,它最终会被迫在那个 Base* 上调用 delete指针。但由于 Base 没有虚拟析构函数,并且指针实际上指向 Derived,因此这是未定义的行为。

但实际上,上面的代码格式正确。 shared_ptr 的模板构造函数采用 Derived* 指针并存储一个自定义删除器,该删除器在原始 Derived* 上调用 delete > 指针,这很好。

关于c++ - 广义复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44227121/

相关文章:

C++ 模板和 header 分配

c# - 如何将项目模板中的文件夹重命名为项目名称? (visual studio模板定制)

java - 多态参数适用于父类(super class),但不适用于子类

python - 如何更好的基于配置文件实例化不同的子类?

c++ - 简化路径的算法

c++ - 带有现有 C/C++ 项目的 Eclipse CDT

c++ - 在 C++ 中使用具有相同方法的类中调用非成员函数

c++ - 删除目录的功能仅在调试完成后将其删除 C++

c++ - C++中模板转换 `operator const T &`的属性是什么?

c# - 需要帮助理解实现接口(interface)的抽象类