在 C++ 中有条件地定义引用变量
conditionally define reference variables in 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;
}
}
可以用不同的方式完成吗?我只需要在必要时创建一个新对象 mat2
,这样我就可以节省内存。
构造该代码的更好方法如何:
std::vector<std::vector<int>> mat =
val ? std::vector<std::vector<int>>(10, std::vector<int>(10, 0))
: SomeFunction();
完全不需要参考资料!
如果您总是需要周围的默认矢量,并且只在有条件的情况下需要其他矢量,那么您可以像这样做一些更长的事情:
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());
(注意一个空的vector在栈上只占非常小的space。)
我喜欢把我的功能分成尽可能多的小功能。
还有一个选择。
std::vector<std::vector<int> > getDefaultArray()
{
return std::vector<std::vector<int> >(10, std::vector<int>(10, 0));
}
std::vector<std::vector<int> > getArray(bool val)
{
return val ? getDefaultArray() : Somefunction();
}
void test(bool val)
{
std::vector<std::vector<int> > mat = getArray(val);
// Use mat
// ...
}
如果你真的想使用引用,你可以先使用指针来解决这个问题:
std::vector<std::vector<int> > mat(10, std::vector<int>(10, 0));
std::vector<std::vector<int> > *p_mat;
if(val)
p_mat = &mat;
else
p_mat = &SomeFunction();
std::vector<std::vector<int> > &ref_mat = *p_mat;
我正在尝试以与此程序类似的方式有条件地初始化引用变量,但无法通过以下方式进行:
#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;
}
}
可以用不同的方式完成吗?我只需要在必要时创建一个新对象 mat2
,这样我就可以节省内存。
构造该代码的更好方法如何:
std::vector<std::vector<int>> mat =
val ? std::vector<std::vector<int>>(10, std::vector<int>(10, 0))
: SomeFunction();
完全不需要参考资料!
如果您总是需要周围的默认矢量,并且只在有条件的情况下需要其他矢量,那么您可以像这样做一些更长的事情:
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());
(注意一个空的vector在栈上只占非常小的space。)
我喜欢把我的功能分成尽可能多的小功能。
还有一个选择。
std::vector<std::vector<int> > getDefaultArray()
{
return std::vector<std::vector<int> >(10, std::vector<int>(10, 0));
}
std::vector<std::vector<int> > getArray(bool val)
{
return val ? getDefaultArray() : Somefunction();
}
void test(bool val)
{
std::vector<std::vector<int> > mat = getArray(val);
// Use mat
// ...
}
如果你真的想使用引用,你可以先使用指针来解决这个问题:
std::vector<std::vector<int> > mat(10, std::vector<int>(10, 0));
std::vector<std::vector<int> > *p_mat;
if(val)
p_mat = &mat;
else
p_mat = &SomeFunction();
std::vector<std::vector<int> > &ref_mat = *p_mat;