Reputation: 3
I have this kind of templated class
template<class T>
class myClass
{
public:
.
myClass(const T & element);
.
private:
T element;
};
and I use dynamically allocated element as T in main
struct Node
{
.
.
};
int main()
{
myClass<Node*> obj(new Node);
}
How can I free the space taken by new keyword or is it done automatically when destructor of myClass have been called ?
Upvotes: 0
Views: 52
Reputation: 9825
No need to manage memory on your own. Use std::unique_ptr
template<class T>
class myClass
{
public:
myClass(std::unique_ptr<T> ptr) : element(std::move(ptr)) { };
private:
std::unique_ptr<T> element;
};
And use it like this
myClass<Node> obj(std::make_unique<Node>()); // note that I removed the *
Upvotes: 1
Reputation: 872
this is a common question for C++. Take a look here: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#r-resource-management
The CppCoreGuidelines give you a reasonable way on how to deal with memory. Consider reading for RAII and Smart-Pointers (everything included in CppCoreGuidelines).
Upvotes: 0