mardi 26 mars 2019

Safe return and handling of dynamically allocated memory from a function, C++ 11

I am new to C++ and thus new to smart pointers concept and usage as well. I want to allocate memory dynamically for a struct in a function and then once the receiver is done using that memory. I want the unique (not shared) receiver to safely release the memory. Something like the following:

typedef struct {
  int x;
  int y;
} myStruct;

myStruct* initMem(void)
{
   myStruct* result = new myStruct();
   result->x = 12;
   result->y = 14;
   return result;
}

int main()
{
  cout << ">>>>> Main | STARTED <<<<<" << endl;
  myStruct* w = initMem();
  cout << w->x << endl;
  cout << w->y << endl;
  delete w;
  return 1;
}

But I read that playing with raw pointers in C++ for dynamic memory management is not good as C++ has the concept of smart pointers especially for this. Can you please help me in converting the above logic to using smart pointers.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire