【问题标题】:Why is forwarding reference constructor called instead of copy constructor?为什么调用转发引用构造函数而不是复制构造函数?
【发布时间】:2017-09-04 14:06:29
【问题描述】:

给定以下代码

#include <iostream>

using namespace std;

template <typename Type>
struct Something {
    Something() {
        cout << "Something()" << endl;
    }

    template <typename SomethingType>
    Something(SomethingType&&) {
        cout << "Something(SomethingType&&)" << endl;
    }
};

int main() {
    Something<int> something_else{Something<int>{}};
    auto something = Something<int>{};
    Something<int>{something};
    return 0;
}

我得到以下输出

Something()
Something()
Something(SomethingType&&)

为什么复制构造函数被解析为模板化转发引用构造函数而不是移动构造函数?我猜这是因为移动构造函数是隐式定义的,而不是复制构造函数。但是在阅读了在堆栈溢出中未隐式定义复制构造函数的情况后,我仍然感到困惑。

【问题讨论】:

标签: c++ c++11 constructor c++14 implicit-constructor


【解决方案1】:

我猜这是因为隐式定义了移动构造函数而不是复制构造函数。

不,两者都是为 Something 类隐式定义的。

为什么复制构造函数被解析为模板化转发引用构造函数

因为复制构造函数将const Something&amp; 作为其参数。这意味着要调用复制构造函数,需要隐式转换来添加const 限定符。但是转发引用构造函数可以被实例化为以Something&amp;为参数,那么它是一个精确匹配并且在重载决议中获胜。

因此,如果您创建somethingconst,则将在第三种情况下调用隐式定义的复制构造函数,而不是转发引用构造函数。

LIVE

但不是移动构造函数?

因为对于移动构造函数,上述问题并不重要。对于第一种和第二种情况的调用,隐式定义的移动构造函数和转发引用构造函数都是完全匹配的,则非模板移动构造函数获胜。

【讨论】:

猜你喜欢
  • 2012-06-28
  • 2015-06-10
  • 1970-01-01
  • 2013-04-25
  • 2012-04-29
  • 1970-01-01
  • 2012-02-28
  • 1970-01-01
相关资源
最近更新 更多