【问题标题】:map of structs using unique ptr : does not build on visual but works on clang使用唯一 ptr 的结构图:不建立在视觉上,但适用于 clang
【发布时间】:2013-05-18 20:49:54
【问题描述】:

我有这两个简单的代码:

void f(){
    std::map<int,std::unique_ptr<int>> map_;
    std::unique_ptr<int> p;
    map_[42] = std::move(p);
}

确实构建

struct test_s{
    int toto;
    std::unique_ptr<int> tata;
};
void f(){
    std::map<int,test_s> map_;
    test_s p;
    map_[42] = std::move(p);
}

无法构建,因为在视觉 ctp120 上禁止复制 它确实建立在带有 Clang 4.2 的 MAC 上

有人知道我应该改变什么来完成这项工作吗?

【问题讨论】:

    标签: visual-studio-2012 c++11 clang move-semantics unique-ptr


    【解决方案1】:

    显式定义移动构造函数和移动赋值运算符是一种解决方法(用VS2010测试):

    struct test_s{
        int toto;
        std::unique_ptr<int> tata;
        test_s() : toto(0) {}
        test_s& operator=(test_s&& o)
        {
            toto = o.toto;
            tata = std::move(o.tata);
            return *this;
        }
        test_s(test_s&& o) : toto(o.toto), tata(std::move(o.tata)) {}
    };
    

    作为猜测,MSVC 不会自动生成移动操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-26
      • 1970-01-01
      • 2014-11-26
      • 1970-01-01
      相关资源
      最近更新 更多