工厂方法创建shared_ptr对象

Luc*_*raw 1 c++ polymorphism shared-ptr visual-c++

当使用工厂创建对象时,例如在下面的示例中,在某些情况下,shared_ptr显然被返回过程中被删除的对象被删除(在调试期间,对象被创建好,但是当它被分配给this->xs异常时被抛出) .当我更改工厂方法以返回原始指针时,作为代码的Link::xs成员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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bil*_*nch 6

因此,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());
}
Run Code Online (Sandbox Code Playgroud)

或者,甚至更好:

std::shared_ptr<CrossSection> Factory::create(const std::string& type)
{
    if (geom == "circular")
        return std::make_shared<Circular>();
    else
        return std::make_shared<Dummy>();
}
Run Code Online (Sandbox Code Playgroud)