当使用工厂创建对象时,例如在下面的示例中,在某些情况下对象被 shared_ptr
包装显然在返回过程中被删除(在调试期间对象创建正常但当它被分配给 this->xs
抛出异常)。当我更改工厂方法以返回原始指针时,Link::xs
成员(member)成为 unique_ptr
代码运行良好。 shared_ptr
背后发生了什么使它以这种方式运行?是否与shared_ptr<CrossSection>
有关?正在包装 Circular
目的?已使用 MS Visual C++ 2012 完成测试。
class Link
{
private:
std::shared_ptr<xs::CrossSection> xs;
public:
void parseXsection(const std::vector<std::string>& parts);
std::shared_ptr<xs::CrossSection> getXs() { return this->xs; }
};
void Link::parseXsection(const std::vector<std::string>& parts)
{
this->xs = xs::Factory::create(parts[1]);
}
namespace xs
{
class CrossSection
{
};
class Circular : public CrossSection
{
};
class Dummy : public CrossSection
{
};
class Factory
{
public:
static std::shared_ptr<CrossSection> create(const std::string& type);
};
std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
if (geom == "circular")
{
return std::shared_ptr<CrossSection>(new Circular());
}
else
{
return std::shared_ptr<CrossSection>(new Dummy());
}
}
}
最佳答案
因此,Martin 有一个解决析构函数问题的选择。您可以添加一个虚拟析构函数。
但是,因为您使用的是 std::shared_ptr
,它采用了一些类型删除,您可以做一个较小的修复:
std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
if (geom == "circular")
return std::shared_ptr<Circular>(new Circular());
else
return std::shared_ptr<Dummy>(new Dummy());
}
或者,甚至更好:
std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
if (geom == "circular")
return std::make_shared<Circular>();
else
return std::make_shared<Dummy>();
}
关于c++ - 工厂方法创建 shared_ptr 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25084918/