与C ++中的正常指针相比,智能指针的开销是多少? [英] How much is the overhead of smart pointers compared to normal pointers in C++?

查看:146
本文介绍了与C ++中的正常指针相比,智能指针的开销是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与C ++ 11中的正常指针相比,智能指针的开销是多少?换句话说,如果我使用智能指针,我的代码会变慢吗?如果是,是多少慢?

How much is the overhead of smart pointers compared to normal pointers in C++11? In other words, is my code going to be slower if I use smart pointers, and if so, how much slower?

具体来说,我问的是C + +11 std :: shared_ptr std :: unique_ptr

Specifically, I'm asking about the C++11 std::shared_ptr and std::unique_ptr.

显然,被压入堆栈的东西会更大(至少我认为是这样),因为智能指针也需要存储它的内部状态(引用计数等),问题真的是,

例如,我从函数而不是普通指针返回一个智能指针:

For example, I return a smart pointer from a function instead of a normal pointer:

std::shared_ptr<const Value> getValue();
// versus
const Value *getValue();

或者,例如,当我的一个函数接受智能指针作为参数而不是普通指针:

Or, for example, when one of my functions accept a smart pointer as parameter instead of a normal pointer:

void setValue(std::shared_ptr<const Value> val);
// versus
void setValue(const Value *val);


推荐答案

std :: unique_ptr 只有在提供了一些不重要的删除器时才有内存开销。

std::unique_ptr has memory overhead only if you provide it with some non-trivial deleter.

std :: shared_ptr 总是有引用计数器的内存开销,尽管它非常小。

std::shared_ptr always has memory overhead for reference counter, though it is very small.

std :: unique_ptr 时间开销只在构造函数(如果它必须复制提供的删除者)和析构函数(以销毁拥有的对象)。

std::unique_ptr has time overhead only during constructor (if it has to copy the provided deleter) and during destructor (to destroy the owned object).

std :: shared_ptr 在构造函数(创建引用计数器),析构函数(减少引用计数器并可能销毁对象)和赋值运算符(以增加引用计数器)中具有时间开销。

std::shared_ptr has time overhead in constructor (to create the reference counter), in destructor (to decrement the reference counter and possibly destroy the object) and in assignment operator (to increment the reference counter).

请注意,它们都没有时间开销在解引用(在获取对所有对象的引用),而这个操作似乎是最常见的指针。

Note that none of them has time overhead in dereferencing (in getting the reference to owned object), while this operation seems to be the most common for pointers.

总之,有一些开销,但它不应该使代码变慢,除非你不断创建和销毁智能指针。

To sum up, there is some overhead, but it shouldn't make the code slow unless you continuously create and destroy smart pointers.

这篇关于与C ++中的正常指针相比,智能指针的开销是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆