这是一个过度简化,但我无法重新创建问题。
#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;
}
静态检查发现没有错误,并且该程序执行正常。但是,在一个更复杂的程序中,我得到了不可能的segfaults。我试图更改
std::shared_ptr<Derived> sharedObject = std::make_shared<Derived>();
std::shared_ptr<Base> sharedObject = std::make_shared<Derived>();
问题消失了。
我想问一下,我在这里忽略的"升级" shared_ptr
是否有一些问题,或者我的segfaults是否来自其他地方。
要做的一件事是定义基类中的虚拟破坏者,这样,当shared_ptr脱离范围
时,将调用正确的dtorsotoh:似乎是VS2010中的错误,GCC 4.8 Compliles&amp;链接好的
以下代码无法与VS2010链接,错误:
1> derived.obj:错误lnk2005:" public:____thiscall derived :: derived(void)"(?? 0 dedrived @@ qae@xz)已在cpp.obj中定义1> derived.obj:错误lnk2005:" public:virtual __thiscall derived ::〜derived(void)"(?? 1 derevered @@ @@ uae@xz)已在cpp.obj
中定义#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;
}