为什么{}按一阶转换为std :: nullptr_t

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

本文关键字:std nullptr 转换 为什么      更新时间:2023-10-16

此代码:

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

输出:

default ctor
operator=(std::nullptr_t)

为什么选择使用std::nullptr_toperator=

我们有三个候选人:

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

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

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

由于标准转换序列比用户定义的转换序列要好,因此#3胜利。