C++: Difference between revisions

850 bytes added ,  23 October 2019
Line 128: Line 128:
# Using free
# Using free
std::unique_ptr<void *, decltype(std::free) *> my_buffer(std::malloc(10), std::free);
std::unique_ptr<void *, decltype(std::free) *> my_buffer(std::malloc(10), std::free);
</syntaxhighlight>
====Deallocate====
Normally, containers such as <code>std::vector</code> will automatically deallocate memory from the heap when the destructor is called. However, occationally you may want to coarse this deallocation yourself.<br>
There are a few ways to do this:
* Use smart pointers
* Copy-and-swap idiom
* Call a clear/shrink/deallocate function
Example [https://stackoverflow.com/questions/3054567/right-way-to-deallocate-an-stdvector-object Reference]:
<syntaxhighlight>
// Using smart pointers
std::unique_ptr<std::vector<float>> my_vector = make_unique<std::vector<float>>(99);
my_vector->reset();
// Copy-and-swap idiom
std::vector<float> my_vector(99);
std::vector<int>().swap(my_vector);
// Clear and shrink
// Specific to std::vector
std::vector<float> my_vector(99);
my_vector.clear();
my_vector.shrink_to_fit();
</syntaxhighlight>
</syntaxhighlight>