[英]Declaring uninitialized variable which is initialized within a nested scope
I have the following C++ snippet 我有以下C ++代码段
double exetime = 0;
SVDRec R;
{
timer<double> dummy{exetime};
R = svdLAS2();
}
std::cout << exetime << std::endl;
where the constructor of timer
records the time the scoping block was entered, and its destructor (which is called when the block is leaved) computes the passed time and stores it in exetime
. timer
的构造函数在其中记录进入作用域块的时间,而其析构函数(离开该块时将调用它)计算经过的时间并将其存储在exetime
。 R
is only initialized inside the block, and it does not have a default constructor, so the code doesn't compile for this reason. R
仅在块内部初始化,并且它没有默认构造函数,因此由于这个原因,代码无法编译。 But I do not want to initialize R
to some dummy value. 但是我不想将R
初始化为一些虚拟值。
This, too, doesn't compile: 这也不会编译:
double exetime = 0;
SVDRec &&tmpR;
{
timer<double> dummy{exetime};
tmpR = svdLAS2();
}
SVDRec R = tmpR;
std::cout << exetime << std::endl;
I know I could use a pointer but I do not want to use dynamic allocation nor std::unique_ptr. 我知道我可以使用指针,但我不想使用动态分配或std :: unique_ptr。 Is there is anyway to achieve this? 反正有实现这个目标的方法吗?
You can try: 你可以试试:
double exetime = 0;
SVDRec R = [&exetime]()
{
timer<double> dummy{exetime};
return svdLAS2();
}();
std::cout << exetime << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.