New operator in function parameter

I have a function, and this function takes a pointer to a class. the problem is that I am calling the class pointer as follows.

Function (new ChildClass);

the function looks something like this:

void Function (BaseClass *instance)
{
    childClassInstance = instance;
}

The reason I call it the new keyword is because I need it outside of my function. What I wanted to know was. When I am ready to delete an instance. How can i do this? Since this is in a function parameter, how would I like to call it to remove it? or how can I access its location in memory to delete it?

If this is not possible, then what would be the best solution?

+1
source share
3 answers

, . RAII. :

void Function (BaseClass& instance);
//...
ChildClass c;
Function(c);

, new :

ChildClass c;
Function(&c);
+3

. .

ChildClass *c = new ChildClass;
Function(c);
delete c;

, . , , .

ChildClass c;
Function(&c);
+1

If you create an object with a new one, then you must save this pointer somewhere in order to delete it later. There is no other option. But this is one of the things that pointers are complicated for, so you should avoid them if possible. You could avoid new ones, as others have said, or you could use a smart pointer that will automatically delete an object for you.

0
source

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


All Articles