C++初始化一个unique_ptr with int 0问题
C++ initialize a unique_ptr with int 0 problem
环境:C++11/14 和 MacOS Clion
首先,我知道用nullptr
构造一个unique_ptr比用int: 0
构造一个更好,但我只是想知道是什么导致了以下两个编译结果:
// compile just fine
class MyClass {};
void MyFunc(unique_ptr<MyClass>) {
}
int main() {
MyFunc(0);
return 0;
}
// compile error
class MyClass {};
void MyFunc(unique_ptr<MyClass>) {
}
int main() {
MyFunc(int(0));
return 0;
}
后一个错误:
note: candidate function not viable: no known conversion from 'int' to 'unique_ptr' for 1st argument
检查 unique_ptr
的构造函数后,我发现以下候选者:
constexpr unique_ptr( nullptr_t ) noexcept;
所以我进一步尝试:
// good
int main() {
nullptr_t mynullptr(0);
return 0;
}
另一方面:
// error
int main() {
nullptr_t mynullptr(int(0));
return 0;
}
留言:
error: cannot initialize a variable of type 'std::nullptr_t' (aka 'nullptr_t') with an rvalue of type 'int'
nullptr_t mynullptr(int(0));
那么是不是因为nullptr
的初始化导致了编译错误?
感谢 M.M 的评论:
literal 0 may be converted to nullptr ; other integer expressions may not (even if they are constant and have value zero)
环境:C++11/14 和 MacOS Clion
首先,我知道用nullptr
构造一个unique_ptr比用int: 0
构造一个更好,但我只是想知道是什么导致了以下两个编译结果:
// compile just fine
class MyClass {};
void MyFunc(unique_ptr<MyClass>) {
}
int main() {
MyFunc(0);
return 0;
}
// compile error
class MyClass {};
void MyFunc(unique_ptr<MyClass>) {
}
int main() {
MyFunc(int(0));
return 0;
}
后一个错误:
note: candidate function not viable: no known conversion from 'int' to 'unique_ptr' for 1st argument
检查 unique_ptr
的构造函数后,我发现以下候选者:
constexpr unique_ptr( nullptr_t ) noexcept;
所以我进一步尝试:
// good
int main() {
nullptr_t mynullptr(0);
return 0;
}
另一方面:
// error
int main() {
nullptr_t mynullptr(int(0));
return 0;
}
留言:
error: cannot initialize a variable of type 'std::nullptr_t' (aka 'nullptr_t') with an rvalue of type 'int'
nullptr_t mynullptr(int(0));
那么是不是因为nullptr
的初始化导致了编译错误?
感谢 M.M 的评论:
literal 0 may be converted to nullptr ; other integer expressions may not (even if they are constant and have value zero)