向上转换std :: shared_ptr会导致段错误

时间:2012-11-08 00:09:26

标签: c++ c++11 smart-pointers

这是过于简单化,但我无法重现这个问题。

#include <memory>

class Base
{
};
class Derived : public Base
{
};

void doSomethingPolymorphical(std::shared_ptr<Base> basePointer)
{
}

int main(int argc, char** argv)
{
    std::shared_ptr<Derived> sharedObject = std::make_shared<Derived>();
    doSomethingPolymorphical(sharedObject);
    return 0;
}

静态检查没有发现错误,这个程序执行正常。但是在一个更复杂的程序中,我得到了非破坏性的段错误。我试图改变

std::shared_ptr<Derived> sharedObject = std::make_shared<Derived>();

std::shared_ptr<Base> sharedObject = std::make_shared<Derived>();

问题就消失了。

我想问一下,如果我在这里忽略了shared_ptr的“向上转发”问题,或者我的段错误来自其他地方。

1 个答案:

答案 0 :(得分:0)

要做的事情之一就是在基类中定义虚拟析构函数,这样当shared_ptr超出范围时将调用正确的dtors

OTOH: 看起来像VS2010中的bug,gcc 4.8 compiles&amp;链接没关系

以下代码无法与VS2010链接并出现错误:

1&gt; Derived.obj:错误LNK2005:已在cpp.obj中定义的“public:__thiscall Derived :: Derived(void)”(?? 0Derived @@ QAE @ XZ) 1&gt; Derived.obj:错误LNK2005:已在cpp.obj中定义的“public:virtual __thiscall Derived :: ~Derived(void)”(?? 1Derived @@ UAE @ XZ)

#include <memory>
#include <iostream>

class Base
{
public:

    Base()
    {}

    virtual ~Base()
    {}

    virtual void Print() const
    {
        std::cout << "from Base::Print" << std::endl;
    }
};

class Derived : public Base
{
public:
    Derived() : Base()
    {}

    ~Derived()
    {}

    void Print() const
    {
        std::cout << "from Derived::Print" << std::endl;
    }
};

void doSomethingPolymorphical(std::shared_ptr<Base> basePointer)
{
    basePointer->Print();
}

int main(int argc, char** argv)
{
    std::shared_ptr<Derived> sharedObject = std::make_shared<Derived>();
    doSomethingPolymorphical(sharedObject);
    return 0;
}