为什么要调用转发引用构造函数而不是复制构造函数? [英] Why is forwarding reference constructor called instead of copy constructor?

查看:123
本文介绍了为什么要调用转发引用构造函数而不是复制构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下代码

#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&&)

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

Why is the copy constructor being resolved to the templated forwarding reference constructor but not the move constructor? I am guessing that it's because the move constructor was implicitly defined but not the copy constructor. But I am still confused after reading the cases for where the copy constructor is not implicitly defined in stack overflow.

推荐答案

我猜这是因为move构造函数是隐式定义的,而不是复制构造函数.

I am guessing that it's because the move constructor was implicitly defined but not the copy constructor.

否,两者都是为类Something隐式定义的.

No, both are implicitly defined for class Something.

为什么将副本构造函数解析为模板化转发引用构造函数

Why is the copy constructor being resolved to the templated forwarding reference constructor

因为复制构造函数将const Something&作为其参数.这意味着要调用复制构造函数,需要添加const限定符进行隐式转换.但是转发引用构造函数可以实例化为以Something&作为其参数,然后它是完全匹配的,并在重载分辨率中获胜.

Because the copy constructor takes const Something& as its parameter. That means for the copy constructor to be called, implicit conversion is needed for adding const qualifier. But the forwarding reference constructor could be instantiated to take Something& as its parameter, then it's an exact match and wins in the overload resolution.

因此,如果您使something const,则在第3种情况下将调用隐式定义的副本构造函数,而不是转发引用构造函数.

So if you make something const, the implicitly defined copy constructor will be invoked for the 3rd case instead of the forwarding reference constructor.

实时

但不是move构造函数?

but not the move constructor?

因为对于move构造函数,上述问题无关紧要.对于第一种情况和第二种情况的调用,隐式定义的move构造函数和转发引用构造函数都是完全匹配的,然后以非模板的move构造函数为准.

Because for the move constructor the above issue doesn't matter. For the invocation of the 1st and 2nd case, both implicitly defined move constructor and forwarding reference constructor are exact match, then non-template move constructor wins.

这篇关于为什么要调用转发引用构造函数而不是复制构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆