我试过谷歌这个问题,我找不到任何我认为相关的东西.所以我一定在寻找错误的东西; 尽管如此,我还是很欣赏一些建议......
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)
我应该只使用指针,还是完全有效?