【问题标题】:std::unique_ptr and templates: Why won't this code compile?std::unique_ptr 和模板:为什么这段代码不能编译?
【发布时间】:2015-09-08 19:58:58
【问题描述】:

我正在为游戏开发模板化组件系统。它将项目保存在一个向量中,并有两个部分特化:一个用于 POD 类型,另一个使用 std::unique_ptr。 std::unique_ptr 向量的模板化特化无法编译,但在非模板化代码中使用 std::unique_ptr 向量可以正常工作。我一直在寻找解决这个问题的方法,但不幸的是,我对 C++11/C++14 的了解还不够完善;我做错了什么?

最小示例(剥离到问题区域):

#include <vector>
#include <memory>

template<typename T>
class component 
{
    public:
    class handle
    {
    friend class component;
    protected:
        std::size_t inner;
    };

    component<T>::handle add(const T& t)
    {
        items.push_back(t);
        handle h;
        h.inner = items.size() - 1;
        return h;
    }

    protected:
        std::vector<T> items;
};


template<typename T>
class component<std::unique_ptr<T>> 
{
    public:
    class handle
    {
    friend class component;
    protected:
         std::size_t inner;
    };

    component<std::unique_ptr<T>>::handle add(const std::unique_ptr<T>& t)
    {
        items.push_back(std::move(t));
        handle h;
        h.inner = items.size() - 1;
        return h;
    }

    protected:
    std::vector<std::unique_ptr<T>> items;
};

这是测试代码

int main()
{
    // This works fine.
    component<int> pod_component;
    pod_component.add(5);

    // This works, too!
    std::vector<std::unique_ptr<int>> pointer_vector;
    pointer_vector.push_back(std::make_unique<int>(5));

    component<std::unique_ptr<int>> pointer_component;
    // Why doesn't this compile?
    pointer_component.add(std::make_unique<int>(5));

    return 0;
 }

这是 gcc (4.9.3 Gentoo) 的错误输出:

 error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]’
{ ::new((void *)__p) _Up(std::forward<_Args>(__args)...); }

我希望比我更擅长 C++ 的人可以帮助我和未来的读者理解这个棘手的问题。

【问题讨论】:

  • items.push_back(std::move(t)); 回退到复制,因为 t 是 const 引用

标签: c++ templates c++14 unique-ptr


【解决方案1】:

问题出在这里:

component<std::unique_ptr<T>>::handle add(const std::unique_ptr<T>& t)   
{                                 //        |
    items.push_back(std::move(t));// <------+
    // ...

std::move 应用于const 左值返回一个const 右值引用。因此,它受push_back(const value_type&amp;) 重载而不是push_back(value_type&amp;&amp;) 的约束,这意味着它试图复制作为参数传递的unique_ptr。

正确的声明应该如下所示:

component<std::unique_ptr<T>>::handle add(std::unique_ptr<T>&& t)
//                                                         ~^^~

【讨论】:

  • 谢谢!我还发现签名component&lt;std::unique_ptr&lt;T&gt;&gt;::handle add(std::unique_ptr&lt;T&gt; t) 也可以编译。两者在功能上有区别吗?
  • @Colin 没有区别,如果最终 add 函数从其参数中移动
猜你喜欢
  • 2010-11-24
  • 1970-01-01
  • 2012-07-06
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 2015-07-23
  • 1970-01-01
相关资源
最近更新 更多