Posted on 2008-11-23 18:28
Batiliu 閱讀(379)
評論(0) 編輯 收藏 引用 所屬分類:
讀書筆記
operator bool()
有時候,我們需要用戶自定義的類型具有在條件表達式中被自動轉換為bool,以滿足例如:if (p)、if(!p)、while(std::cin>>obj)等慣用代碼。接下來,我們來看看各種各種的解決方案:
- operator int () const
struct X
{
operator int() const;
};
X o;
std::vector<X> v(o); // OMG!無聲無息(編譯器檢查不出)走向錯誤!
- operator void* () const
struct X
{
operator void*() const;
};
X o;
delete o; // OMG!危險!
- operator bool () const
struct X
{
operator bool() const;
};
// 很多人認為讓對象從邏輯上表現為一個布爾值的操作符,還有比operator bool()更適合的嗎?
// 很遺憾,請往下看:
X o1;
X o2;
int i = o1 + o2; // bool可以被隱式地轉換為int
// 還有更糟糕的:
X o1;
Y o2; // Another type
if (o1 == o2) // 很可能是語義上錯誤的代碼
{
...
}
- operator boolean const * () const
struct X
{
private:
struct boolean { private: void operator delete(void*); };
public:
operator boolean const *() const
{
return 0;
}
};
// 很好,該方案是Peter Dimvo在Boost新聞組上提出來的。
// 但基于指針技術的問題在于它們允許向void(const)*轉換,這可能是不希望的轉換。
X o;
void const * p = o;
- operator int boolean::* () const
class X
{
private:
struct boolean { int i; };
public:
operator int boolean::*() const
{
return 1 ? &boolean::i : NULL;
}
};
// 成員函數的指針不管是通過隱式轉換還是顯示轉換,都不能被轉換至常規的指針類型。
// Perfect!它具備了我們對一個"bool"轉換操作符的性質的所有要求
operator ++()
首先,我們來看下重載后置增量操作符的規范形式:
struct X
{
X operator ++(int)
{
X ret(*this);
operator ++();
return ret;
}
};
由于后置式操作符在進行增量/減量操作之前必須先把當前值保留下來,這樣才能夠在增量/減量操作完成后將它返回給調用者,所以它們跟前置式的操作符相比通常具有較高的性能開銷。
那我們有什么辦法能偵測出代碼中對后置操作符的不恰當使用呢?幸運的是,我們在模板的幫助下找到了解決方案:
template<typename V, typename M, typename R = V>
class unused_return_value_monitor
{
public:
typedef unused_return_value_monitor<V, M, R> class_type;
public:
unused_return_value_monitor(R value, M monitor = M())
: m_value(value)
, m_monitor(monitor)
, m_bUsed(false)
{}
unused_return_value_monitor(class_type const& rhs)
: m_value(rhs.m_value)
, m_monitor(rhs.m_monitor)
, m_bUsed(rhs.m_bUsed)
{
rhs.m_bUsed = false;
}
~unused_return_value_monitor()
{
if (!m_bUsed)
{
m_monitor(this, m_value);
}
}
public:
operator V() const
{
m_bUsed = true;
return m_value;
}
private:
R m_value;
M m_monitor;
mutable bool m_bUsed;
// 聲明但不予實現
private:
unused_return_value_monitor& operator =(class_type const& rhs);
};
// 由于這是一個會影響效率的偵測裝置,所以我們將它整合進類的調試版本中。
class X
{
private:
struct use_monitor
{
void operator ()(void const* instance, X const& value) const
{
// 出現“敵情”,輸出到調試窗口或日志文件中。
cout << "Warnning!" << endl;
}
};
public:
X& operator ++()
{
// ...
return *this;
}
#ifdef _DEBUG
unused_return_value_monitor<X, use_monitor> operator ++(int)
#else
X operator ++(int)
#endif
{
X ret(*this);
operator ++();
return ret;
}
};