简体   繁体   English

声明在嵌套范围内初始化的未初始化变量

[英]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.

相关问题 实际初始化的未初始化局部变量? - Uninitialized local variable that is actually initialized? 在类范围内声明与类属性同名的局部变量 - Declaring a local variable within class scope with same name as a class attribute 是什么导致已初始化的类成员变量在方法调用中变为(或出现)未初始化? - What causes an initialized class member variable to become (or appear) uninitialized within a method call? 在没有null构造函数的情况下声明未初始化的变量 - Declaring an uninitialized variable without a null constructor 声明变量时:此范围内未声明的变量 - When declaring a variable: variable not declared in this scope 尽管已初始化变量,编译器仍会给出未初始化的局部变量错误 - compiler gives uninitialized local variable error despite initialized variable 已初始化与未初始化的全局变量,存储在 RAM 的哪一部分? - Initialized vs uninitialized global variables, in which part of the RAM are the stored? 使用未初始化的局部变量? 还没有初始化? 有什么问题 - Uninitialized local variable used? yet initialized? whats the problem 警告:未初始化的变量//但我已经初始化了! C ++编译器错误? - warning: uninitialized variable //But I have initialized ! C++ Compiler bug? 声明友元函数时的变量范围错误 - Variable scope error when declaring friend function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM