gpt4 book ai didi

c++ - 为什么 {} 一阶转换为 std::nullptr_t?

转载 作者:IT老高 更新时间:2023-10-28 21:52:44 26 4
gpt4 key购买 nike

这段代码:

#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)

为什么选择带有 std::nullptr_toperator=

最佳答案

我们有三个候选人:

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

对于#1 和#2,{}导致user-defined conversion sequence .

但是,对于#3,{}standard conversion sequence因为nullptr_t不是类类型。

因为标准转换序列是better than用户定义的转换序列,#3 获胜。

关于c++ - 为什么 {} 一阶转换为 std::nullptr_t?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46082318/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com