尝试使用std::shared_ptr
转发std::static_pointer_cast
时发生了段错误,其中派生类还包含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;
}
答案 0 :(得分: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;
}