I realize that there is a (Sometimes significant) performance hit for creating, assigning, copying, and destroying a std::tr1::shared_ptr or boost::shared_ptr (due to the reference counting mechanisms). Is it correct that once constructed, accessing the pointer wrapped by a shared_ptr has no performance penalty?
in other words: given
std::tr1::shared_ptr<myClass> SharedA(new myClass);
myClass *NakedA = new myClass;
does
SharedA->someClassMember
have the same 开发者_StackOverflow中文版overhead as
NakedA->someClassMember
?
In an optimized build without debugging support, there shouldn't be any overhead. You can find out by taking a look at the implementation you are using. Chances are, its operator->
overload just returns the pointer to the pointed-to object and its operator*
overload just dereferences this pointer.
(This is what the Visual C++ 2010 implementation of std::shared_ptr
does: each of those overloaded operators just calls a "get" function which just returns the pointer; there is no locking or other overhead of any kind. Other implementations may be different.)
An unoptimized build may not inline the operator overload and if your implementation has extra debugging support that you enable, it may perform extra checks (e.g., perhaps an assert if you dereference a null pointer).
All of the member functions of a smart pointer, including the dereference operator, can be inlined. Any good compiler should optimize away the abstraction.
精彩评论