【发布时间】: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<Base>() ) {} 行中的error: allocating an object of abstract class type 'Base'。
所以,问题是:如何使用std::shared_ptr 进行这项工作?
【问题讨论】:
-
默认构造函数初始化程序不正确,根本不应该存在。
std::shared_ptr<>像任何指针一样,可以包含 nullptr,并且会使用默认构造。 -
base 的虚拟析构函数在哪里?
-
@spin_eight 好点,但
shared_ptr不需要。
标签: c++ c++11 shared-ptr pure-virtual