1

I am trying to use shared_ptr to replace the C-Style pointer to avoid the memory leak.

T** list_of_T;

This is my old code. And I try to use shared_ptr in this way:

vector<shared_ptr<T>> vector_Of_Tptr;

But I think vector will use more memory, and I should rewrite some of my code. So could I change the code in some way like?

shared_ptr<shared_ptr<T> []> shared_list_of_T;

Is this a good practice?

Charlie
  • 13
  • 3
  • I'm not sure what the `std::shared_ptr` does for you here unless you have other objects pointing at the same arrays? Otherwise a `std::vector>` would make more sense. However that's not particularly efficient so you may want to consider wrapping a one dimension array in a class that presents a two dimensional view, a bit like this: https://stackoverflow.com/questions/53038457/what-is-the-best-modern-c-approach-to-construct-and-manipulate-a-2d-array/53038618#53038618 – Galik Mar 03 '19 at 04:46
  • 1
    Before worrying about the memory overhead, you need to figure out (and tell us) what the lifetime of these objects is and what changes the data structure needs to support. – Davis Herring Mar 04 '19 at 02:05

0 Answers0