c++ - default behaviour for (bool) cast -



c++ - default behaviour for (bool) cast -

classes in stl, such unique_ptr show examples such as:

// unique_ptr constructor illustration #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* homecoming 0; }

the line:

std::cout << "u1: " << (u1?"not null":"null") << '\n';

shows unique_ptr u1 beingness straight cast false if tracking null pointer.

i have seen behaviour used in other custom classes. how managed , operator decides whether direct cast bool such returns true or false?

it implemented fellow member conversion operator of form explicit operator bool() const;. whether returns true or false implemented in logic of class itself. example, class has bool conversion operator returns true if it's info fellow member has value 42, , false otherwise:

struct foo { explicit operator bool() const { homecoming 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"); }

c++ c++11 operator-overloading std

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -