取消引用 std::tr1:shared_ptr 与取消引用裸指针有什么不同吗?
我意识到创建、分配、复制和销毁 std::tr1::shared_ptr 或 boost::shared_ptr (由于引用计数机制)会对性能造成(有时很严重)影响。一旦构造完毕,访问由shared_ptr包装的指针不会有性能损失,这是否正确?
换句话说:给定的
std::tr1::shared_ptr<myClass> SharedA(new myClass);
myClass *NakedA = new myClass;
开销
SharedA->someClassMember
相同。
NakedA->someClassMember
与?
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 overhead as
NakedA->someClassMember
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在没有调试支持的优化构建中,不应该有任何开销。您可以通过查看您正在使用的实现来找到答案。有可能,其
operator->
重载仅返回指向所指向对象的指针,而其operator*
重载仅取消引用该指针。(这就是
std::shared_ptr
的 Visual C++ 2010 实现所做的:每个重载运算符仅调用一个“get”函数,该函数仅返回指针;没有任何锁定或其他开销其他实现可能有所不同。)未优化的构建可能不会内联运算符重载,并且如果您的实现启用了额外的调试支持,它可能会执行额外的检查(例如,如果您取消引用空指针,则可能会执行断言)。
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 itsoperator*
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.