为什么{}按一阶转换为std :: nullptr_t
Why {} converted to std::nullptr_t in first order?
此代码:
#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_t
的operator=
?
我们有三个候选人:
-
operator=(T const& )
-
operator=(std::vector<int> const& )
-
operator=(std::nullptr_t )
对于#1和#2,{}
都导致用户定义的转换序列。
但是,对于#3,{}
是标准转换序列,因为nullptr_t
不是类型。
由于标准转换序列比用户定义的转换序列要好,因此#3胜利。
相关文章:
- 为什么"weak.lock()"返回"nullptr" "auto weak=std::make_shared<int>(42);"的定义?
- 使用 nullptr 作为 std::unordered_map 的键有什么后果吗?
- 为什么 char 可以在 std::array 中初始化为 nullptr,而不是单独初始化?
- C++ - 向量中的 std::unique_ptr <> 为 nullptr
- std::rethrow_exception(nullptr) 未定义的行为还是bad_exception?
- std::string::c_str() 曾经返回 nullptr 吗?
- 'const std::string&s = nullptr' 如何作为可选参数工作
- 使用 std::可选标准化,我们可以停止在新代码中使用 nullptr 并弃用它吗?
- 一旦 std::weak_ptr 上的锁返回了 nullptr,它是否还会再次成为非 null
- std::unique_ptr 是否在其析构函数中将其基础指针设置为 nullptr?
- std :: malloc在失败时返回null或nullptr吗?
- 在C 11中,Dynamic_cast返回null或std :: nullptr会发生失败
- 在为其分配一个新值之前,应将`nullptr`分配给`sTD :: simelod_ptr`
- 为什么可以将NULLPTR分配给STD :: String
- C 如何检测何时将nullptr传递到预期std :: string的功能
- 为什么 empty() std::basic_string c_str() 不是 nullptr?
- 将 nullptr 分配给 std::string 是安全的
- std::将成员函数绑定到 nullptr 处的实例,导致看似随机的 this 指针
- 将 NULL/nullptr 转换为 std::function<>& 时失败
- 当使用const std::string&作为方法参数类型时,处理nullptr const char*的正确方法是什么?