【发布时间】:2017-05-01 09:33:49
【问题描述】:
尝试使用std::static_pointer_cast 向下转换std::shared_ptr 时发生段错误,其中派生类也包含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;
}
【问题讨论】:
-
您的
static_pointer_cast具有未定义的行为,当然,因为pB实际上并不指向pD类型的对象。 -
我明白了。我显然误解了
std::static_pointer_cast的作用。你会如何建议我实现我想要的,即将底层的Base“升级”到Derived,最后产生std::shared_ptr<Derived>? -
问题是你实际上是在构造一个
Base,所以当你将它转换为Derived(有效)你在访问它时会得到未定义的行为,因为Derived的内存实际上从来没有分配。在这种情况下,您会遇到段错误。 -
确实如此,虽然我不确定它指的是
boost::shared_ptrs -
@WilliamHandley:“我明显误解了 std::static_pointer_cast 的作用是什么。” 仅供参考:
static_pointer_cast的重点是完全按照static_cast如果您使用的是非智能指针,就可以了。因此,如果Base *pB = new Base; Derived *pD = static_cast<Derived*>(pB)不合法(实际上不合法),那么shared_ptr等效项也不合法。
标签: c++ c++11 casting shared-ptr weak-ptr