Nic*_*ton 16 c++ pointers initialization reference
我试过谷歌这个问题,我找不到任何我认为相关的东西.所以我一定在寻找错误的东西; 尽管如此,我还是很欣赏一些建议......
Foobar &foobar = *new Foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
它只是我还是看起来很臭?
我知道该new
关键字设计用于指针(如此):
Foobar *foobar = new Foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
但是,如果您不需要该实例上的指针,并且您想使用引用呢?或者,您是否需要显式初始化它(很像局部变量); 如果是这种情况,如果我想用参数初始化怎么办?
以下不起作用(除非我做错了):
// the last argument is of type: int
Foobar &foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
...给出编译器错误:
初始化表达式列表作为复合表达式处理从'int'类型的临时表中无效初始化类型'Foobar&'的非const引用
而且这似乎不起作用:
Foobar &foobar = Foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
...给出编译器错误:
错误:从'Foobar'类型的临时类型'Foobar&'类型的非const引用无效初始化
请记住我正在返回此值,因此我不想使用局部变量; 我想在堆上使用一个值,而不是堆栈:
Foobar &helloWorld()
{
Foobar &foobar = *new Foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
Run Code Online (Sandbox Code Playgroud)
我应该只使用指针,还是完全有效?
小智 11
为什么你认为你需要使用新的和引用?为什么不:
Foobar foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
对于您的函数 - 返回一个值:
Foobar helloWorld()
{
Foobar foobar(someArg, anotherArg);
foobar.HelloWorld();
return foobar;
}
Run Code Online (Sandbox Code Playgroud)
或指针:
Foobar * helloWorld()
{
Foobar * foobar = new Foobar(someArg, anotherArg);
foobar->HelloWorld();
return foobar;
}
Run Code Online (Sandbox Code Playgroud)
如果这样做 - 调用者负责在某个时刻删除分配的对象.
从非成员函数返回的地方通常不能合理地使用引用,因为您想要引用的内容通常不再存在.
是的,那很臭!
如果你是'new'的东西,请将它指定给指针(或智能指针类型),因为它需要再次删除以避免内存泄漏.引用通常不被认为是您需要再次删除的内容,因此如果其他人看到该代码(将新的对象分配给引用),它可能会混淆它们.
你可以做...
const Foobar &foobar = Foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
...如果你真的想要一个参考.请注意,一旦foobar超出范围,它引用的临时对象将会死亡.但是,当你可以直截了当地写下时,写作中没有太多意义:
Foobar foobar(someArg, anotherArg);
Run Code Online (Sandbox Code Playgroud)
您可能实际上并不需要引用...它们通常(但不是唯一地)用于方法参数的类型.这样您就可以传递看起来像对象的东西,但只有指针的大小,并且方法可以修改.引用的引用主要是为了让你编写一个拷贝构造函数(我不会在这里解释!).