[英]Does boost::optional trigger a ref count on shared_ptr?
我正在嘗試獲取一個函數來從我的地圖中返回一個可選值。 所以像這樣:
boost::optional<V> findValue(const K& key) {
boost::optional<V> ret;
auto it = map.find(key);
if (it != map.end()) {
ret = it->second;
}
return ret;
}
如果V
恰好是某種類型的shared_ptr
類型,則ret
的賦值是否會觸發引用計數?
是的,它必須。 boost::optional
存儲副本,所以對於一個shared_ptr
,這意味着在副本shared_ptr
,這意味着引用計數必須增加。
請注意,只要boost::optional
為空,即它不包含shared_ptr
的值,就不會有引用計數錯誤的對象。 換句話說,一個空boost::optional
不包含(空或其他方式) shared_ptr
。
請求的“語義”無法真正起作用,因為您在地圖中保留了一個shared_ptr
並返回了shared_ptr
。
但是,您可以返回boost::optional<const V&>
:
boost::optional<const V&> findValue(const K& key) {
auto it = map.find(key);
if (it != map.end()) {
return boost::optional<const V&>( it->second );
}
return boost::optional<const V&>();
}
但請確保在保留/使用時參考仍然有效。
是。 復制共享指針(在這種情況下通過復制初始化optional
對象中包含的指針)將增加使用計數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.