c++ - Does boost::optional trigger a ref count on shared_ptr? -


i'm trying function return optional value map. this:

boost::optional<v> findvalue(const k& key) {     boost::optional<v> ret;     auto = map.find(key);     if (it != map.end()) {         ret = it->second;     }     return ret; } 

if v happens shared_ptr type of kind, assignment ret trigger reference count?

yes, has to. boost::optional stores copy, shared_ptr, means there copy of shared_ptr , means reference count must increased.

note long boost::optional empty, i.e., doesn't contain value of shared_ptr, there no object reference count fiddled with. in other words, empty boost::optional not contain (empty or otherwise) shared_ptr.

the requested "semantics" can't work because keep 1 shared_ptr in map , return shared_ptr.

however, may return boost::optional<const v&>:

boost::optional<const v&> findvalue(const k& key) {     auto = map.find(key);     if (it != map.end()) {         return boost::optional<const v&>( it->second );     }     return boost::optional<const v&>(); } 

but make sure reference remains valid while keep/use it.


Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -