[英]Why is there no operator<< for std::unique_ptr?
C ++ 11標准中的[util.smartptr.shared.io]要求operator<<
for shared_ptr
s:
template<class E, class T, class Y>
basic_ostream<E, T>& operator<< (basic_ostream<E, T>& os, shared_ptr<Y> const& p);
但是,除非我錯過它,否則我在[unique.ptr]中看不到類似內容,en.cppreference.com上的引用也同意。 差異有原因嗎?
差異有原因嗎?
不,沒有。 就像make_unique
一樣,這是一個“疏忽”,應該在將來添加(如果有人可能會費心去發送提案)。
在此期間,您可以輸出ptr.get()
,或者 - 如果不害怕未定義的行為:
#if __cplusplus <= 201600 // Some time in future
namespace std {
template <class E, class T, class Y, class D>
basic_ostream<E, T>& operator<< (basic_ostream<E, T>& os,
unique_ptr<Y, D> const& p) {
return os << p.get();
}
}
#endif
根據[namespace.std]未定義:
除非另有說明,否則如果向命名空間
std
[...]添加聲明或定義,則C ++程序的行為是未定義的。
......以上內容並不是特別允許的。 但是,這種未定義的行為很好,可以在沒有任何影響的情況下調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.