Spa*_*rky 2 c++ operator-overloading std c++11
stl中的类,例如unique_ptr,偶尔会显示如下示例:
// unique_ptr constructor example
#include <iostream>
#include <memory>
int main () {
std::default_delete<int> d;
std::unique_ptr<int> u1;
std::unique_ptr<int> u2 (nullptr);
std::unique_ptr<int> u3 (new int);
std::unique_ptr<int> u4 (new int, d);
std::unique_ptr<int> u5 (new int, std::default_delete<int>());
std::unique_ptr<int> u6 (std::move(u5));
std::unique_ptr<void> u7 (std::move(u6));
std::unique_ptr<int> u8 (std::auto_ptr<int>(new int));
std::cout << "u1: " << (u1?"not null":"null") << '\n';
std::cout << "u2: " << (u2?"not null":"null") << '\n';
std::cout << "u3: " << (u3?"not null":"null") << '\n';
std::cout << "u4: " << (u4?"not null":"null") << '\n';
std::cout << "u5: " << (u5?"not null":"null") << '\n';
std::cout << "u6: " << (u6?"not null":"null") << '\n';
std::cout << "u7: " << (u7?"not null":"null") << '\n';
std::cout << "u8: " << (u8?"not null":"null") << '\n';
*emphasized text* return 0;
}
Run Code Online (Sandbox Code Playgroud)
这条线:
std::cout << "u1: " << (u1?"not null":"null") << '\n';
Run Code Online (Sandbox Code Playgroud)
显示unique_ptr u1如果跟踪空指针则直接转换为false.
我在其他自定义类中看到过这种行为.如何管理以及哪个运算符决定直接转换为bool(例如this)是返回true还是false?
它是作为表单的成员转换运算符实现的explicit operator bool() const;
.它是返回true还是false是在类本身的逻辑中实现的.例如,此类有一个bool转换运算符,true
如果它的数据成员有值则返回42
,false
否则:
struct Foo
{
explicit operator bool() const { return n==42; }
int n;
};
#include <iostream>
int main()
{
Foo f0{12};
Foo f1{42};
std::cout << (f0 ? "true\n" : "false\n");
std::cout << (f1 ? "true\n" : "false\n");
}
Run Code Online (Sandbox Code Playgroud)