new operator in function parameter

丶灬走出姿态 提交于 2019-12-06 03:47:04

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);

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);

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.

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