将共享的_ptr降低到包含feal_ptr C 11的派生类
Downcasting a shared_ptr to a derived class containing a weak_ptr c++11
我在尝试使用std::static_pointer_cast
降低std::shared_ptr
时发生了一个segfault,其中派生的类还包含 std::weak_ptr
。
这是MWE:
#include<iostream>
#include<memory>
struct Base {};
struct Derived : Base
{
std::weak_ptr<int> wp;
};
int main()
{
auto pB = std::make_shared<Base>(); // Create a pointer to Base class instance
auto pD = std::static_pointer_cast<Derived>(pB); // Downcast this to a Derived class instance
auto pint = std::make_shared<int>(0); // Define a pointer to an integer
std::cout << "assigning pint" << std::endl;
pD->wp = pint; //Attempt to assign member of Derived
std::cout << "Did not segfault" << std::endl;
return 0;
}
这会编译和有效,但是我不确定它是否是'好'C 11
#include<iostream>
#include<memory>
struct Base {};
struct Derived : Base
{
Derived(std::shared_ptr<Base> b) : Base{*b} {}
std::weak_ptr<int> wp;
};
int main()
{
auto pB = std::make_shared<Base>(); // Create a pointer to Base class instance
auto pD = std::make_shared<Derived>(pB);
auto pint = std::make_shared<int>(0); // Define a pointer to an integer
std::cout << "assigning pint" << std::endl;
pD->wp = pint;
std::cout << "Did not segfault" << std::endl;
return 0;
}
相关文章:
- 为什么使用 "this" 指针调用派生成员函数?
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 在派生函数中指定void*参数
- 如何通过派生类函数更改基类中的向量
- 如何委托派生类使用其父构造函数?
- 如何使用单独文件中的派生类访问友元函数对象
- 派生类销毁的最佳实践是什么
- 如何使用基类指针引用派生类成员
- 派生类是否可以在抽象工厂设计模式中具有数据成员
- 使用基类指针创建对象时,缺少派生类析构函数
- 如何引用基类的派生类?
- 存储模板类型以强制转换回派生<T>
- 需要从 istream 和 ostream 派生 iostream
- 在 C++ 中用派生类型重写成员函数
- 如何将派生类从基 ptr 分配给 nlohmann::json
- C++ 类型转换基础 PTR 到派生 PTR 保存在引用类中
- 通过基类的 ptr 调用派生类的方法
- 如何访问受保护的基类函数,从派生类通过基类ptr
- 基类或派生类:谁应该拥有派生的ptr(指向不同的类)
- 将派生类的ptr类型转换为ptr类型