我是否正确初始化了我的C ++参考变量? [英] Am I initializing my C++ reference variables correctly?
问题描述
我已尝试通过Google搜索此问题,但找不到与我相关的任何内容.所以我一定在寻找错误的东西;尽管如此,我还是很乐意的...
I've tried to Google this issue, and I can't find anything that I see as relevant. So I must be looking for the wrong thing; none the less, I'd appreciate some advice...
Foobar &foobar = *new Foobar(someArg, anotherArg);
是我还是看起来很臭?
我了解new
关键字是专为与指针一起使用而设计的:
I understand that the new
keyword is designed for use with pointers (as such):
Foobar *foobar = new Foobar(someArg, anotherArg);
但是,如果您不需要该实例上的指针,而想使用引用,该怎么办?或者,是不需要显式初始化它的情况(很像局部变量)?如果是这种情况,我要用参数初始化怎么办?
But what if you don't require a pointer on that instance, and you would like to use a reference instead? Or, is it the case that you don't need to explicitly initialize it (much like local variables); and if this is the case, what if I want to initialize with parameters?
以下内容不起作用(除非我做错了):
The following does not work (unless I'm doing something wrong):
// the last argument is of type: int
Foobar &foobar(someArg, anotherArg);
...给出编译器错误:
... gives the compiler error:
初始化器表达式列表被视为复合表达式 类型为"Foobar&"的非常量引用的无效初始化 来自"int"类型的临时
initializer expression list treated as compound expression invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘int’
这似乎也不起作用:
Foobar &foobar = Foobar(someArg, anotherArg);
...给出编译器错误:
... gives the compiler error:
错误:类型的非常量引用的无效初始化 类型为"Foobar"的临时广告中的"Foobar&"
error: invalid initialization of non-const reference of type ‘Foobar&’ from a temporary of type ‘Foobar’
更新1:
请记住,我要返回此值,所以我不想使用局部变量;我想在堆而不是堆栈上使用一个值:
Update 1:
Bare in mind that I am returning this value, so I don't want to use a local variable; I want to use a value on the heap, not the stack:
Foobar &helloWorld()
{
Foobar &foobar = *new Foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
我应该只使用指针,还是完全有效?
Should I just be using pointers instead, or is this completely valid?
推荐答案
为什么您认为根本需要使用new和reference?为什么不呢?
Why do you think you need to use new and references at all? Why not:
Foobar foobar(someArg, anotherArg);
对于您的函数-返回一个值:
For your function - return a value:
Foobar helloWorld()
{
Foobar foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
或指针:
Foobar * helloWorld()
{
Foobar * foobar = new Foobar(someArg, anotherArg);
foobar->HelloWorld();
return foobar;
}
如果执行此操作,则调用方有责任在某个时候删除分配的对象.
If you do this - the caller is responsible for deleting the allocated object at some point.
从非成员函数返回的地方通常不会明智地使用引用,因为您想引用的东西通常不再存在.
Return from a non-member function is one place where references can typically not be used sensibly, as the thing you would like to refer to usually no longer exists.
这篇关于我是否正确初始化了我的C ++参考变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!