C++:使用直接返回shared_ptr的函数的值是一个坏主意吗?
例如:
boost::shared_ptr<int> test() {
boost::shared_ptr<int> x(new int(3));
return x;
}
void function() {
int y = *test();
...
}
使用shared_ptr来避免复制整个对象也是一个坏主意吗?例如,像矩阵/图像的向量。
For example:
boost::shared_ptr<int> test() {
boost::shared_ptr<int> x(new int(3));
return x;
}
void function() {
int y = *test();
...
}
Is it also a bad idea to use shared_ptr to avoid copying the whole object? Like a vector of matrices/images for example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般情况下,不会。您的示例复制
shared_ptr
的内容,然后删除原始值。现在,这里更大的问题是,为
int
进行动态内存分配的效率非常低,但我假设您没有在实际代码中这样做。 :)In the general case, no. Your example copies the contents of the
shared_ptr
, and then the original value is deleted.Now, the bigger issue here is that it's fantastically inefficient to do a dynamic memory allocation for an
int
, but I'm assuming you're not doing that in real code. :)在您的示例中,这很好,因为您正在制作
int
的副本。如果您将 int 作为引用,那么在该行之后,它将是一个悬空引用,因为共享指针将超出范围,从而删除其目标。
使用
shared_ptr
将避免复制,就像使用裸指针将避免复制一样 - 决定是否要避免复制(首先),然后选择应使用哪种类型的指针。对于矩阵或图像向量,您可能需要使用
boost::shared_ptr
的std::vector
或boost::ptr_vector
>,或其他一些可以让您轻松管理内存的容器。In your example, that's fine, since you're making a copy of the
int
.If you get the
int
as a reference, then after that line, it would be a dangling reference, since the shared pointer would go out of scope, deleting its target.Using
shared_ptr
will avoid copying just as using a naked pointer will avoid copying - decide whether you want to avoid copying (first), and then choose which sort of pointer you should use.For a vector of matrices or images, you may want to use a
std::vector
ofboost::shared_ptr
, or aboost::ptr_vector
, or some other container that makes the memory management easy for you.我想说的是,这是一个坏主意。
如果您使用指针,有两个原因。 1. 您的对象可能为 null,或者 2. 您有一个不想复制的大对象。
直接使用该值并不是一个好主意,因为您不知道它是否为空。
I would say that yes, it is a bad idea.
If you're using a pointer there are 2 reasons. 1. Your object might be null, or 2. you have a big object that you don't want to copy.
It's rarely a good idea to use the value directly since you don't know if it's null or not.