【问题标题】:Pure virtual and std::shared_ptr纯虚拟和 std::shared_ptr
【发布时间】:2014-05-25 14:39:35
【问题描述】:

可能我只是错过了文档中的某些内容(或者只是无法进行适当的 Google 搜索),但我遇到了 shared_ptr 和纯虚函数的问题。

一个简短的例子:

class Base
{
public:
    virtual int stuff() = 0;
};

class Derived : public Base
{
public:
    virtual int stuff() {return 6;}
};

class Container
{
public:
    Container() : m_x( 0 ) {}
    Container(Base* x) : m_x(x) {} 

private:
    Base* m_x;
};

由于我想使用新的花哨std::shared_ptr,我将Container 修改为:

class Container
{
public:
    Container() : m_x( std::make_shared<Base>() ) {}
    Container(const std::shared_ptr<Base>& x) : m_x(x) {} 

private:
    std::shared_ptr<Base> m_x;
};

显然,这不起作用,clang 和其他编译器抱怨:Container() : m_x( std::make_shared&lt;Base&gt;() ) {} 行中的error: allocating an object of abstract class type 'Base'

所以,问题是:如何使用std::shared_ptr 进行这项工作?

【问题讨论】:

  • 默认构造函数初始化程序不正确,根本不应该存在。 std::shared_ptr&lt;&gt; 像任何指针一样,可以包含 nullptr,并且会使用默认构造。
  • base 的虚拟析构函数在哪里?
  • @spin_eight 好点,但shared_ptr 不需要。

标签: c++ c++11 shared-ptr pure-virtual


【解决方案1】:

你的问题在这里:

Container() : m_x( std::make_shared<Base>() ) {}

您不能创建 Base 的对象。你想要的是一个空的shared_ptr。所以这样做。

Container() : m_x( std::shared_ptr<Base>() ) {}

或者这样做。

Container() : m_x() {}

相等。

【讨论】:

  • 是的......显然我需要一杯咖啡 :) 谢谢!
  • 或者干脆Container() {}
【解决方案2】:

std::make_shared&lt;Base&gt;() 等价于new Base()。你想要的是要么完全省略 m_x 初始化(默认构造函数将初始化为空),要么显式执行:

Container() : m_x(nullptr) {}

【讨论】:

    【解决方案3】:

    使用模板构造函数直接构造对象。
    所以,你不能有一个默认的构造函数,除非

    • B 变得非抽象,
    • 您决定选择一个具体的首选派生类,或者
    • 您接受 0 初始化 m_x

    【讨论】:

      猜你喜欢
      • 2010-11-21
      • 2018-01-02
      • 2011-04-19
      • 1970-01-01
      • 2013-06-12
      • 2013-04-16
      • 1970-01-01
      相关资源
      最近更新 更多