Is it necessary to delete for new arrays new created in a vector?

I am trying to create some dynamic arrays for a void ** dataset.

std::vector<void*> data;
data.push_back(new double[1024]);  // array of doubles
data.push_back(new short[1024]);   // array of shorts

Use for cleaning

data.clear();

Or each of the new (s) needs to be removed, and if so, how to do it?

+4
source share
4 answers

Use for cleaning

data.clear();

This will remove all pointers from the vector. If any of them are the only copies that point to their respective dynamic objects, then these objects can no longer be destroyed and their memory can not be freed. This is called a memory leak.

Or you need to delete all new (s)

Yes. Each time the expression new[]must be exactly one delete[]. If not delete[], then there is a leak.

, ?

. , , . , ( ) .

void. void , .

delete[] static_cast<double*>(data[0]);
delete[] static_cast<short* >(data[1]);

, , , - , void . - RAII, std::vector:

std::vector<double> doubles(1024);
std::vector<short>  shorts (1024);
std::vector<void*>  data{doubles.data(), shorts.data()};

, , std::vector. , doubles shorts , data .

+4

,

, , void*, , - . C ++, , - !

void , ++.

, , , :

class C1 {
public: 
    C1() { cout<<"  C1 object constructed"<<endl; } 
    ~C1() { cout<<"  C1 object destroyed"<<endl; }
};

- , .

1:

C1, , :

C1 *p = new C1[2];   // every new []
delete[] p;          // requires delete[]

2: , :

, . , , , , :

; :

   vector<C1*> v; 
   v.push_back(new C1[2]);   // C1 objects are created 
   v.clear();                // pointers are lost but C1 objects are not derleted.  

clear, : C1 :

   for (auto &x:v)
       delete[]x; 
   v.clear(); 

3: void * :

, void*, C1, :

std::vector<void*> data;
data.push_back(new C1[2]);   // yes, creating works and ponter is in ector
for (auto &x:data) 
       delete[]x;           // ouch, deletes a void* so it doesn't know that it a C1 object
data.clear();

?

, , , :

  • .
  • , ,
  • boost::variant

, , .

+2

, operator delete. , , , , ?

, std:: unique_ptr

+1

- , , new. , new[], delete[]. , ... , vector ( ), ( ), . ** array<void*>, double (void* , double) vector .

vector::vector<T>(const T v[], const size_t sz);

vector<double> :

const double initial[] = { 109.8, 98.5, 87.5 };
const size_t initial_sz = sizeof initial / sizeof initial[0];
vector<double> v(initial, initial_sz);

, , :

vector<double> v;
v.push_back(109.8);
...
v.push_back(87.5);

, :

vector<double> v(another_double_container.begin(), another_double_container.end());

double [] , double s.

, , . ( ) ( , )

+1

Source: https://habr.com/ru/post/1692170/


All Articles