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

vla*_*don 20 c++ c++14

这段代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

产出:

default ctor
operator=(std::nullptr_t)
Run Code Online (Sandbox Code Playgroud)

为什么operator=std::nullptr_t选择?

Bar*_*rry 18

我们有三个候选人:

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

对于#1和#2,都会{}导致用户定义的转换序列.

但是,对于#3,{}标准转换序列,因为nullptr_t它不是类类型.

由于标准转换序列优于用户定义的转换序列,因此#3获胜.