C ++不会通过取消注释move运算符来编译

时间:2016-07-16 19:31:23

标签: c++ templates c++11 copy-constructor move-constructor

我有以下代码:

template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X(const S<T> & y) : x(y.x) {}

    // Uncomment and it does not compile anymore
    // X(X&& z) : x(z.x) {}

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

你可以解释为什么一旦取消注释指定的代码就不能编译它吗?

2 个答案:

答案 0 :(得分:3)

复制构造函数被隐式声明为已删除,因为您声明了一个移动构造函数。

添加一个默认(或用户定义的)复制构造函数,它可以正常编译:

X(const X<T>&)=default;

答案 1 :(得分:2)

Humam Helfawi明白了这一点。

我试着完成他的回答。

Svalorzen:看看这段代码

#include <iostream>

template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X (const S<T> & y) : x(y.x)
     { std::cout << "templated constructor" << std::endl; }

    X (const X<T> & y) : x(y.x)
     { std::cout << "copy constructor" << std::endl; }

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

输出是&#34;复制构造函数&#34;。

当编译器找到匹配的模板化函数和匹配的普通(无模板)函数时,请选择plain作为更具体的。

现在删除复制构造函数的定义

#include <iostream>

template <typename T>
struct X {
    X() : x(5) {}

    template <template <typename> class S>
    X (const S<T> & y) : x(y.x)
     { std::cout << "templated constructor" << std::endl; }

    T x;
};

int main ()
{
    X<int> y;
    auto x = y;
    return 0;
}

你得到的例子没有移动构造函数,并且添加了cout(&#34;模板化构造函数&#34;)。

您可以看到输出为空。

那是因为编译器选择了作为默认版本隐式存在的复制构造函数。

当您添加移动构造函数时,您偶然将标记为已删除的复制构造函数。但复制构造函数始终存在(即使标记为已删除),编译器也会考虑它。因此,当编译器尝试实现&#34; x = y&#34;时,匹配您的模板化构造函数,匹配复制构造函数,选择复制构造函数(更具体),看看是否已删除并给出错误。

添加

X (const X<T> &) = default;

允许编译器使用复制构造函数。

p.s:抱歉我的英语不好。