函数参数中的新运算符 [英] new operator in function parameter

查看:87
本文介绍了函数参数中的新运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,该函数接受一个类指针。问题是我像这样调用类指针。

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

此函数看起来像这样

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

我使用new关键字调用它的原因是因为我需要它我的功能。我想知道的是。当我准备删除实例时。我怎么去呢?因为它在函数参数,我怎么去调用它以删除它?

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?

推荐答案

这是可能的,但也有一个更好的解决方案。 使用RAII。或通过引用传递参数:

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

即使您保留了指针,也不必创建一个新的实例 new 以传递指针作为参数:

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

这篇关于函数参数中的新运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆