有条件地在C++中定义引用变量

Cau*_*chy 1 c++

我试图以与此程序类似的方式有条件地初始化引用变量,但不可能以下列方式执行:

#include <vector>

void test(bool val){

  std::vector<std::vector<int> > mat(10, std::vector<int>(10, 0));
  std::vector<std::vector<int> > &ref_mat; // This is not allowed

  if(val){
    ref_mat = mat;
  }else{
    std::vector<std::vector<int> > mat2 = Somefunction(); // The returned 2D vector from some function
    ref_mat = mat2;
  }

}
Run Code Online (Sandbox Code Playgroud)

可以用不同的方式完成吗?我需要只mat2在必要时创建一个新对象,这样我就可以节省内存.

Ker*_* SB 9

如何更好地构建代码:

std::vector<std::vector<int>> mat =
     val ? std::vector<std::vector<int>>(10, std::vector<int>(10, 0))
         : SomeFunction();
Run Code Online (Sandbox Code Playgroud)

根本不需要参考!


如果你总是需要默认向量,并且只是有条件地需要另一个向量,那么你可以做一些更长的事情:

std::vector<std::vector<int>> mat_dflt(10, std::vector<int>(10, 0));
std::vector<std::vector<int>> mat_cond;  // small when empty!

auto & mat = val ? mat_dflt : (mat_cond = SomeFunction());
Run Code Online (Sandbox Code Playgroud)

(请注意,空向量仅占用堆栈上的非常小的空间.)