这段代码:
#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=
的参数?
{}
到std::nullptr_t
是标准转换(实际上是恒等转换,[over.ics.list]),但其他转换是用户定义的,因为它们导致用户定义的类型。 - Kerrek SBT
时,它是一个模板参数。这让我有点困惑。 - Mark Ransom