【发布时间】:2011-05-07 03:56:36
【问题描述】:
最近几周,我发现自己到处都在使用很多 const。不仅在方法或参数声明中,甚至在临时变量中也是如此。
让我用一个简单的函数来说明。
我曾经写过:
// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
unsigned int result1 = p1.computeResult();
unsigned int result2 = p2.computeResult();
// Well this function could be in one single line but
// assume it does more complex operations
return result1 + result2;
}
但现在更像是:
// A dummy function that sums some computation results
unsigned int sum_results(const Operation& p1, const Operation& p2)
{
const unsigned int result1 = p1.computeResult();
const unsigned int result2 = p2.computeResult();
// Well this function could be in one single line but
// assume it does more complex operations
return result1 + result2;
}
后者对我来说更有意义,而且似乎不太容易出错。 (我承认在这个例子中,这并不重要)但是我见过 很少 代码示例,其中 const 用于临时/局部变量。我想知道为什么。
这不是常见的情况有什么原因吗?我滥用const 吗?还是只有我看错了样本?
【问题讨论】:
-
intinunsigned int没有提供新的或有用的信息,您应该删除不必要的噪音。