使用cin时是否需要将一个变量存储两次?

Is it necessary to store a variable twice when using cin?

我正在努力完成 "Accelerated C++",我正在将我对章末练习的答案与找到的答案进行比较 here。在为行和列填充创建用户输入时,我写道:

int colpad;
cout << "Please enter the number of columns to pad: ";
cin >> colpad;
int rowpad;
cout << "Please enter the number of rows to pad: ";
cin >> rowpad;

然后在函数的其余部分继续使用 rowpad 和 colpad。这对我有用。

然而,上述站点解决方案的作者做了我所做的,然后添加(为清楚起见更改了变量名称):

const int rowpad = inrowpad; // vertical padding
const int colpad = incolpad; // horizontal padding

他的解决方案也很有效。我的问题是:我是否应该将 colpad 和 rowpad 的值再次存储为 const?这不就是占用额外的内存吗?

使用 const 是保护输入值以后不被更改的好方法。鉴于您提供的网站上的示例程序,没有理由添加新的 const 变量,是的,它会在执行期间消耗几个额外的代码字节 space 和内存。

如果以后您想将变量或指针传递给其他函数,您可以考虑使用 const 来保护指针和引用。但是按照示例所示进行操作并没有什么坏处,而且您的问题是正确的。

也直接回答您的主题行:不,没有必要。

此类构造通常在编译期间 "optimized away"。这意味着,在您的二进制程序中,通常会有一个变量副本。

因此,只要您不对非常 space 复杂性(数组、树、图形...)的结构进行不必要的复制,就不必担心一两个额外的问题变量。

没有必要将值存储到 const 版本中。使用 const 对象可以防止意外更改,并且如果编译器可以确定用于初始化 const 对象的变量不会更改,则在函数内它可能不会使用额外的内存。

顺便说一句,虽然代码在不同方面是错误的:你应该总是验证after读取操作是否成功:

if (!(std::cin >> colpad)) {
    // deal with the read failure
}

额外的内存将是微不足道的,编译器可能会优化掉它,但使用 const 会稍微减少出错的机会。

我想知道在同一范围内为同一事物使用两个变量所增加的复杂性是否值得。

我更愿意将非常量变量提取到一个单独的函数中:

int getInt() {
  int in;
  if(cin >> in)
    return in;
   ...  // handle errors
}

cout << "Please enter the number of columns to pad: ";
const int colpad = getInt();
cout << "Please enter the number of rows to pad: ";
const int rowpad = getInt();

然后主作用域中只有一个变量,它的额外好处是代码重复减少了一点。

我可能会定义一个函数而不是 2 个变量:

int getIntFromUserInput()
{
    int inputValue(0);
    std::cin >> inputValue;
    return inputValue;
}

可以如下使用:

std::cout << "Please enter the number of columns to pad: ";
const int numColumnsToPad(getIntFromUserInput());
std::cout << "Please enter the number of rows to pad: ";
std::const int numRowsToPad(getIntFromUserInput());

这样您就可以将输入的结果存储为 const,而不必担心不必要的内存使用。