jellespijker / VisionSoilAnalyzer

Soil analyzer using an USB microscope - for Linux PC and Beaglebone Black
4 stars 1 forks source link

make the vector<Particles> in Sample a pointer vector #13

Closed jellespijker closed 9 years ago

jellespijker commented 9 years ago

http://www.frogatto.com/?p=26

Using a vector of shared_ptr removes the possibility of leaking memory because you forgot to walk the vector and call delete on each element. Let's walk through a slightly modified version of the example line-by-line.

typedef boost::shared_ptr gate_ptr; Create an alias for the shared pointer type. This avoids the ugliness in the C++ language that results from typing std::vectorboost::shared_ptr and forgetting the space between the closing greater-than signs.

std::vector<gate_ptr> vec;

Creates an empty vector of boost::shared_ptr objects.

gate_ptr ptr(new ANDgate);

Allocate a new ANDgate instance and store it into a shared_ptr. The reason for doing this separately is to prevent a problem that can occur if an operation throws. This isn't possible in this example. The Boost shared_ptr "Best Practices" explain why it is a best practice to allocate into a free-standing object instead of a temporary.

vec.push_back(ptr);

This creates a new shared pointer in the vector and copies ptr into it. The reference counting in the guts of shared_ptr ensures that the allocated object inside of ptr is safely transferred into the vector.

What is not explained is that the destructor for shared_ptr ensures that the allocated memory is deleted. This is where the memory leak is avoided. The destructor for std::vector ensures that the destructor for T is called for every element stored in the vector. However, the destructor for a pointer (e.g., gate*) does not delete the memory that you had allocated. That is what you are trying to avoid by using shared_ptr or ptr_vector.

jellespijker commented 9 years ago

http://stackoverflow.com/questions/3476938/example-to-use-shared-ptr

jellespijker commented 9 years ago

not longer relevant