[英]default behaviour for (bool) cast
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;
}
這條線:
std::cout << "u1: " << (u1?"not null":"null") << '\n';
顯示unique_ptr u1如果跟蹤空指針則直接轉換為false。
我在其他自定義類中看到過這種行為。 如何管理以及哪個運算符決定直接轉換為bool(例如this)是返回true還是false?
它被實現為形式為explicit operator bool() const;
的成員轉換運算explicit operator bool() const;
。 它是返回true還是false是在類本身的邏輯中實現的。 例如,此類有一個bool轉換運算符,如果它的數據成員的值為42
則返回true
否則返回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");
}
operator bool();
它是鍵入bool
的標准強制轉換運算符。
以下是如何使用它的示例:
class Checked
{
bool state;
public:
Checked(bool _state) : state(_state) { }
explicit operator bool() const {
return state;
}
};
Checked c (true);
if (c)
cout << "true";
請注意explicit
關鍵字。 它出現在C ++ 11中,允許將類安全地轉換為bool,簡而言之就是在邏輯上下文中發生,例如if()
, while()
等。如果沒有explicit
,可能會發生壞事,因為有一個將bool
隱式轉換為數字類型。 在C ++ 03及更早版本中,重載operator ! ()
更安全operator ! ()
operator ! ()
,然后進行測試, if (!!c)
。
轉換運算符用於此功能:
operator bool(){ return false; }
在C ++ 11中,您也可以將它們explicit
explicit operator bool(){ return true; }
隱式轉換運算符是一種容易出錯的嘗試。 考慮一下unique_ptr
是否有一個隱含的轉換運算符來bool,你可以做一些無意義的事情,比如...
std::unique_ptr<Thing> x;
int y = 7 + x;
在上面的例子中, y
將等於7
+(如果x為null則為0,如果x為非null,則為1)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.