Reputation: 113
I kind of understand the fact that the wrapped STL containers of a class will be automatically destroyed when an instance of that class goes out of scope. Thus I don't have to write a destructor when the class only wraps STL containers. But what if the class also have to manage some pointer(s)?
Say in some CUDA development, I want a class to handle a device pointer and an STL container as well.
class Image{
private:
float *data_device;
std::array<int, 2> shape;
public:
// some constructors and methods
~Image(){
cudaFree(data_device);
// what to do with the STL array?
}
};
In the above case, I need the destructor to free the memory for data_device
. But should I deal with the STL array? If so, how can I destroy the shape
properly?
Upvotes: 1
Views: 287
Reputation: 62576
You can imagine that the closing brace of a destructor additionally has calls to each member's (and base's) destructor, in the reverse order of construction.
As such you don't need to do anything extra to a properly designed member, which all the std
containers are. But let's back up a little.
But what if the class also have to manage some pointer(s)?
You shouldn't write such a class. Instead you use a class whose sole job is to manage exactly one pointer as an alternative to "some pointer". As a bonus, you now don't have to worry about double-free, because Image
does not have a default copy constructor
// cuda Deleter for std::unique_ptr
struct CudaFree
{
void operator()(float * ptr) { cudaFree(ptr); }
}
class Image{
private:
std::unique_ptr<float, CudaFree> data_device;
std::array<int, 2> shape;
public:
Image(/* ? */)
: data_device(cudaAlloc()/* ? */),
shape(/* ? */)
{/* ? */}
// similarly other constructors
// other members
// implicit destructor does the right thing
};
Upvotes: 3
Reputation: 385098
You are right to create a destructor to manually tear down anything your class manages.
However, doing so does not prevent everything else from being destructed. Your members will still be automatically destructed after the destructor runs; your destructor is in addition.
So you've done it right.
Upvotes: 3
Reputation: 17483
But should I deal with the STL array?
No, you shouldn't.
std::array
destructor destroys every element of the array automatically.
Upvotes: 4