简体   繁体   English

为什么{}按顺序转换为std :: nullptr_t?

[英]Why {} converted to std::nullptr_t in first order?

This code: 这段代码:

#include <iostream>
#include <vector>

using namespace std;

void dump(const std::string& s) {
    cout << s << endl;
}

class T {
public:
    T() {
        dump("default ctor");
    }

    T(std::nullptr_t) {
        dump("ctor from nullptr_t");
    }

    T(const T&) {
        dump("copy ctor");
    }

    T& operator=(const T&) {
        dump("copy operator=");
        return *this;
    }

    T& operator=(std::nullptr_t) {
        dump("operator=(std::nullptr_t)");
        return *this;
    }

    T& operator=(const std::vector<int>&) {
        dump("operator=(vector)");
        return *this;
    }
};

int main() {
    T t0;

    t0 = {};

    return 0;
}

outputs : 产出

default ctor
operator=(std::nullptr_t)

why operator= with std::nullptr_t was selected? 为什么选择operator= with std::nullptr_t

We have three candidates: 我们有三个候选人:

  1. operator=(T const& )
  2. operator=(std::vector<int> const& )
  3. operator=(std::nullptr_t )

For both #1 and #2, {} leads to a user-defined conversion sequence . 对于#1和#2, {}导致用户定义的转换序列

However, for #3, {} is a standard conversion sequence because nullptr_t is not a class type. 但是,对于#3, {}标准转换序列,因为nullptr_t不是类类型。

Since a standard conversion sequence is better than a user-defined conversion sequence, #3 wins. 由于标准转换序列优于用户定义的转换序列,因此#3获胜。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM