new operator in function parameter

穿精又带淫゛_ 提交于 2019-12-07 18:07:11

问题


I have a function and that function takes in a class pointer. the problem is that I call the class pointer like this.

Function (new ChildClass);

the function looks something like this

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

the reason why I call it with the new keyword is because I need it outside my function. What I wanted to know was. When I'm ready to delete instance. How would I go about it? Since it's in the function parameter, how would I go about calling it in order to delete it? or how would I be able to access it's location in memory to be able to delete it?

If this is not possible what would be a better solution?


回答1:


It is possible, but there's also a better solution. Use RAII. Or pass the parameter by reference:

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

Even if you do keep a pointer, you don't have to create a new instance with new to pass a pointer as parameter:

ChildClass c;
Function(&c);



回答2:


You can declare a variable to store your pointer before you call your function. Then you can delete it after your function returns.

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

But, if this is your idiom, then just use an automatic instance. Then, when it falls out of scope, your object is deleted automatically.

ChildClass c;
Function(&c);



回答3:


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



来源:https://stackoverflow.com/questions/11854529/new-operator-in-function-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!