Reputation: 53
I know basically delete is only required when I allocate something using new. However, I'm not certain about how to deallocate smart pointers and those classes which contain smart pointers as their members. So, how can I properly implement the destructors in the following classes?
template <typename T>
class Array {
public:
Array(const unsigned int length){
T* ptr = (T*)malloc(sizeof(T)*length);
array = std::shared_ptr<T>(
new(ptr) T[length],
[](T* ptr){free(ptr);}
);
}
~Array(){
// Q1 how should I properly implement this destructor?
}
private:
std::shared_ptr<T> array;
};
class Example{
public:
Example(){
...
}
~Example(){
// Q2 how should I properly implement this destructor?
}
private:
Array<float> bufferFloatArray;
Array<float>* bufferFloatArrayPtr;
std::shared_ptr<float> bufferFloatPtr;
}
Upvotes: 3
Views: 5779
Reputation: 20569
Note: The answer by @gimme_danger refers to an old version of the question. Here's the answer for the new version.
The
T* ptr = (T*)malloc(sizeof(T)*length);
array = std::shared_ptr<T>(
new(ptr) T[length],
[](T* ptr){ /*...*/ }
);
You first allocate some memory using malloc
, then use the placement-new syntax to call the constructor of T
. You need to do both in the deleter.
[](T* ptr) {
std::destroy_n(ptr, length);
std::free(ptr);
}
You don't need a destructor. The destructor of shared_ptr
is destroyed automatically. By the way, your class has pointer semantics, i.e., two instances may share the same memory, which is probably not desired.
Upvotes: 1
Reputation: 798
Smart pointers automatically invoke their destructors. So you don't need to implement ~Array()
, however in class Example you use raw pointer (Array<float>* bufferFloatArrayPtr)
, which should be properly deallocated in ~Example()
.
PS Note that you made an error in class Array implementation. Use delete[] ptr
instead of free(ptr)
in shared_ptr
delete-expression to avoid memory leak.
Upvotes: 2