纯虚拟和std::shared_ptr
Pure virtual and std::shared_ptr
可能我只是错过了文档中的一些内容(或者只是无法进行正确的Google serach),但我对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
实现这一点?
您的问题在这里:
Container() : m_x( std::make_shared<Base>() ) {}
不能创建Base对象。你想要的是一个空的shared_ptr
。那就这么做吧。
Container() : m_x( std::shared_ptr<Base>() ) {}
或者这样做。
Container() : m_x() {}
这是平等的。
std::make_shared<Base>()
等效于new Base()
。您想要的是完全省略m_x
初始化(默认构造函数会将其初始化为空),或者显式执行:
Container() : m_x(nullptr) {}
使用模板化构造函数直接构造对象
因此,除非,否则不能有默认构造函数
- B变得非抽象
- 你决定选择一个具体的、受欢迎的派生类,或者
- 您接受0初始化CCD_ 11
相关文章:
- CLANG 编译器 说:变量"PTR"可能未初始化
- 在以唯一ptr为值的C++映射中,动态内存何时会被销毁
- 将 ptr 传递给 ptr 到 A 作为参数传递给 A 的函数是不好的做法吗?
- 为共享 ptr 向量实现复制 c'tor?
- 字符和整数中 **(ptr+1) 的值差异
- C++:在不中断共享的情况下通过引用传递共享 PTR?
- 如何将派生类从基 ptr 分配给 nlohmann::json
- 引用 std::shared:ptr 以避免引用计数
- 为什么我不能在不进行任何转换的情况下将浮点数放入任何类型的 ptr 中?
- 在调用函数时,ptr** 和 ptr*& 之间是否有区别,或者首选C++?
- 另一种类型的智能ptr,比如具有弱refs的unique_ptr
- 尝试打印出 *ptr++ 的值,以了解它是如何工作的
- 如何控制共享 ptr 引用计数?
- dopen():不以 root 身份运行时"failed to map segment from shared object"
- C++中的指针否定 (!ptr == NULL)
- 从const ptr*转换为ptr*时出现问题
- 无法使用 libtool 将 -shared 参数传递给 g++
- boost::shared_ptr和std::shared-ptr的同居
- 我可以用std::shared_ptr而不是boost::shared-ptr构建boost库吗
- shared-ptr-C++shared_ptr与unique_ptr用于资源管理