c++ - 工厂方法创建 shared_ptr 对象

标签 c++ visual-c++ polymorphism shared-ptr

当使用工厂创建对象时,例如在下面的示例中,在某些情况下对象被 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/

相关文章:

c++ - Eclipse不会在断点处停止并将线程状态置于Running : User Request

c++ - visual c 中的静态库链接失败

c++ - 对 C++ 多态、可查找、二进制 I/O 接口(interface)的建议

c++ - 虚函数机制实现

c++ - 在全局/函数范围内声明变量。堆栈差异?

c++ - 在另一个窗口中运行 ncurses 程序时,有什么方法可以使用 cout 进行调试吗?

c++ - <algorithm> 中的 Visual Studio 2008 错误? includes 算法似乎无意中交换了第 3795 行迭代器的顺序

c++ - 关于数据对齐的困惑

c++ - C++ 中的 vector 和多态性

从组合中的另一个类重写 C++ 方法