Abdullah Cevizli
Abdullah Cevizli

Reputation: 3

If dynamically allocated element used in templated class how can I deallocate or does it deallocate automatically?

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

Answers (2)

Timo
Timo

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

jonas_toth
jonas_toth

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

Related Questions