【问题标题】:Should this simple structure have an implicit move constructor?这个简单的结构应该有一个隐式的移动构造函数吗?
【发布时间】:2015-11-20 07:34:45
【问题描述】:

在本次测试中:

#include <string>

struct thing {
    std::string name_;
};

class test {
    thing id_;
public:
    test(thing id) : id_{std::move(id)} {}
};

我希望 struct thing 有一个隐式的移动构造函数,以便 class test 可以使用 std::move() 来初始化它的数据成员。

Clang 版本 3.4.1 给出了这个错误:

error: no viable conversion from 'typename remove_reference<thing&>::type' (aka 'thing') to 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char> >')

问题可以通过在struct thing中添加移动构造函数来解决,当然也需要添加转换构造函数和显式默认的复制构造函数。

我不明白为什么我不能隐式移动 struct thing

【问题讨论】:

  • 你用的是什么编译器? ideone.com 编译得很好。 thing 肯定有隐式移动构造函数,但你的编译器将 id_{std::move(id)} 解释为聚合初始化。
  • id_(std::move(id)) (用括号代替花括号)有效。等待language-lawyer 澄清为什么聚合初始化会覆盖移动构造,或者它是否是一个错误:)
  • @Quentin 我有一个聚合初始化盲点。我看不到它。谢谢,现在一切正常。
  • another Richard Smith(Clang 的主要作者之一)问 Clang 相关问题真是令人困惑:)

标签: c++11 language-lawyer


【解决方案1】:

您正在使用大括号初始化 - id_{std::move(id)}。在您的情况下,好像 struct thing 是一个 POD(普通旧数据),这意味着 C++ 编译器尝试初始化第一个成员 - std::string name_ 而不是使用 struct thing 对象的默认构造函数。 Read more about aggregates and PODs.

在这种情况下,由于大括号,class test 的构造函数相当于这样:

class test {
    thing id_;
public:
    test(thing id) {
        id_.name_ = std::move(id); // Notice that this causes
                                   // the "no viable conversion" error
    }
};

解决方案 1: 您需要通过使用括号而不是大括号来明确声明您要使用默认的 struct thing 构造函数:

#include <string>

struct thing {
    std::string name_;
};

class test {
    thing id_;
public:
    test(thing id) : id_(std::move(id)) {} // Default c-tor will be used
};

解决方案 2:您还可以声明 struct thing 的用户定义构造函数,使其成为非 POD:

#include <string>

struct thing {
    std::string name_;
    thing(thing&&) {} // Used-defined move constructor
};

class test {
    thing id_;
public:
    test(thing id) : id_{std::move(id)} {} // You can use braces again
};

【讨论】:

    猜你喜欢
    • 2013-08-08
    • 2020-09-07
    • 2012-06-12
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-09-04
    • 2012-11-09
    相关资源
    最近更新 更多