嘿,我得到一个关于下一个代码中发生了什么的问题:
typedef struct {
double re,im;
} Complex;
Complex ComplexCreate(double r=0.,doublei=0.)
{
Complex c;
c.re=r;
c.im=i;
return c; // problem with this line
// my question is : is c getting duplicated and returning or does it return nothing
// when i we go back to the main
}
Run Code Online (Sandbox Code Playgroud)
我知道在c ++中,我可以而且应该使用类,这只是我想要了解的一个测试.在此先感谢您的帮助
如果未启用优化,则会生成并返回c的副本.如果命名返回值优化(NRVO)可用,则编译器可以忽略该副本.
除此之外,为什么带有构造函数的类并不复杂:
class Complex
{
public:
Complex( double r = 0.0, double i = 0.0 )
: re( r )
, im( i )
{}
double re;
double im;
};
Run Code Online (Sandbox Code Playgroud)
然后,如果你仍然需要像Complex ComplexCreate这样的函数(double r = 0.,doublei = 0.),它看起来像:
Complex ComplexCreate( double r= 0.0, double i = 0.0 )
{
return Complex( r, i );
}
Run Code Online (Sandbox Code Playgroud)
这里返回一个未命名的临时变量是指没有命名返回值优化(NRVO)编译器将有更好的机会来了的Elid本地对象的副本 - 而不是直接对呼叫者工作栈.