Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

c++ - Why is forwarding reference constructor called instead of copy constructor?

Given the following code

#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;
}

I get the following output

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

No, both are implicitly defined for class Something.

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

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.

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

LIVE

but not the move constructor?

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...