C ++: Is it nice to use the value of a function that returns shared_ptr directly?

For instance:

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? As a vector of matrices / images, for example.

+4
source share
3 answers

Generally not. Your example copies the contents of shared_ptr , and then the original value is deleted.

Now, the big problem here is that it is fantastically inefficient for allocating dynamic memory for an int , but I assume you are not doing this in real code. :)

+4
source

This is fine in your example, since you are making a copy of int .

If you get int as a link, then after this line it will be a chatty link, since the general pointer will go out of scope by deleting it.

Is it also a bad idea to use shared_ptr to avoid copying the whole object? As a vector of matrices / images, for example.

Using shared_ptr will prevent copying, since using an open pointer will avoid copying - decide if you want to avoid copying (first), and then choose which type of pointer you should use.

For matrix or image vectors, you can use std::vector from boost::shared_ptr , or boost::ptr_vector , or some other container that simplifies memory management.

+2
source

I would say yes, this is a bad idea.

If you use a pointer, there are two reasons. 1. Your object may be empty or 2. You have a large object that you do not want to copy.

It is rarely a good idea to use a value directly, as you do not know if it is null or not.

+1
source

All Articles