【问题标题】:using make_unique and make_shared statically doesn't work静态使用 make_unique 和 make_shared 不起作用
【发布时间】:2017-06-02 03:44:28
【问题描述】:

我正在尝试学习可以在 C++ 中使用的各种工厂模式。我不确定为什么我不能返回一个唯一的 ptr。我可以很好地返回一个共享的ptr。这是我的代码:

class FactoryMethodExample {
    FactoryMethodExample() {}
public:
    static FactoryMethodExample get_instance() {
            return {};
    }

    static FactoryMethodExample * get_pointer() {
        return new FactoryMethodExample;
    }

    static unique_ptr<FactoryMethodExample> get_unique_instance() {
        return make_unique<FactoryMethodExample>();
    }

    static shared_ptr<FactoryMethodExample> get_shared_instance() {
        return shared_ptr<FactoryMethodExample>();
    }

    void verify() {
        cout << "I exist" << endl;
    }
};

此代码无法编译。我收到此错误:

error: calling a private constructor of class 'FactoryMethodExample'
return unique_ptr<_Tp>(new _Tp(_VSTD::forward<_Args>(__args)...));

【问题讨论】:

  • make_unique 不能使用私有构造函数:它不是类的朋友。你必须做老式的return std::unique_ptr&lt;FactoryMethodExample&gt;(new FactoryMethodExample());
  • 另请注意,您的 get_shared_instance() 实际上并没有返回实例 - 它返回一个空共享指针。
  • 如果有std::make_shared() 可用,则使用return std::make_shared&lt;FactoryMethodExample&gt;()(在使构造函数可访问之后),否则使用return shared_ptr&lt;FactoryMethodExample&gt;(new FactoryMethodExample);
  • @IgorTandetnik 谢谢,你的老式方法奏效了。但是我无法通过朋友类方法使其工作。你能解释一下吗?
  • 不要那样做;它是非便携式的。即使你设法与std::make_unique 成为朋友,它也可以合法地将实际工作委托给一些内部帮助函数(它不会是朋友,让你从头开始)。所以你的程序可以用一些标准库实现编译,但不能用其他实现。

标签: c++ c++11


【解决方案1】:

首先,您的shared_ptrunique_ptr 示例不可比较。

make_unique 创建一个用值初始化的unique_ptr

shared_ptr 只是 shared_ptr 类的构造函数调用,这将使其初始化为空指针。

这就是您得到两个不同结果的原因。

你有一个错误的原因是因为你有一个私有构造函数。最简单的解决方案是结交 make_unique(和 make_shared)朋友。

请参阅以下问题以获得一些指导:How to make std::make_unique a friend of my class

此外,您的函数名称可能会产生误导。 get_shared_instance 意味着每次都会返回同一个实例,我想你想在哪里返回一个新实例的 shared_ptr?

【讨论】:

  • 我无法在朋友班上完成这项工作。我只是添加friend std::unique_ptr&lt;FactoryMethodExample&gt; std::make_unique&lt;FactoryMethodExample&gt;(); 吗?
猜你喜欢
  • 1970-01-01
  • 2011-07-22
  • 2019-10-09
  • 1970-01-01
  • 1970-01-01
  • 2014-12-10
  • 2016-04-03
  • 2017-05-19
  • 1970-01-01
相关资源
最近更新 更多