0

There is a template class A:

template<typename T>
class A {
public:
    T t;
    A(T t) {
        this->t = t;
        cout << "A constructor" << endl;
    }
    ~A() {
        cout << "A destructor" << endl;
    }
};

t is the member of class A, what if t is a pointer points to dynamically allocated memory so that the default destructor can't free it, for example:

A<SomeType*> a(new SomeType());

Because we don't know if t is a pointer or not, so we can't just make the deconstructor like this:

~A() {
    delete t;
    cout << "A destructor" << endl;
}

My question is how to guarantee that there is no memory leak no matter t is a pointer or not

cong
  • 1,105
  • 1
  • 12
  • 29
  • 4
    `A` should not be responsible for de-allocating memory that it didn't allocate. Read up on [RAII](http://en.cppreference.com/w/cpp/language/raii) and [smart pointers](http://en.cppreference.com/w/cpp/memory). – Sander De Dycker May 08 '17 at 13:19
  • 1
    Also http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three (if you still choose to implement it your way) and it's *destructor*, not *deconstructor*. – LogicStuff May 08 '17 at 13:19

1 Answers1

6

If T is a raw pointer then, in "Modern C++", you should assume that it doesn't own the memory location it points to. If you need ownership semantics, you should use smart pointers like std::unique_ptr and std::shared_ptr - those clean up after themselves and can be trivially used as T without changing A.

If you have raw pointer that you have no control upon and owns some memory, then you should wrap it inside a smart pointer before passing it to A.

tl;dr: T needs to take care of its own resources and you should assume it does.

Vittorio Romeo
  • 90,666
  • 33
  • 258
  • 416