Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rationale for the shared_ptr atomic functions taking pointer instead of reference

As you can see here, shared_ptr is passed as a pointer instead of reference. Also note that

All these functions invoke undefined behavior if p is a null pointer.

So why pointer? I think in C++, reference should be preferred unless there are specific reasons to use pointer.

like image 350
Lingxi Avatar asked Feb 12 '18 14:02

Lingxi


1 Answers

template< class T >
bool atomic_is_lock_free( const std::shared_ptr<T>* p );

takes a pointer to a smart pointer because this is a special case of the more generic atomic_is_lock_free:

template< class Atomic >
bool atomic_is_lock_free(const Atomic* obj)

where Atomic is std::shared_ptr<T>. The same goes for all template function atomic_*.

As user luk32 noticed, this only answer the question partially: "While [...] such signature is demanded by template interface, it immediately begs to reapply the question and ask why the generic interface wasn't designed to use reference."

Well, those <atomic> signatures come originally from the GCC C extensions [citation needed] functions __sync_*. Since C does not have references, the C++ committee might [citation needed] had the will to mimic those functions and provide an easy way to update code relying on those builtins.

like image 89
YSC Avatar answered Sep 20 '22 13:09

YSC