你用const能做到什么程度?你只是在必要的时候才把函数变成const,还是从头到尾到处都用它?例如,想象一个简单的变异子,它接受一个布尔参数:

void SetValue(const bool b) { my_val_ = b; }

这个const真的有用吗?就我个人而言,我选择广泛地使用它,包括参数,但在这种情况下,我想知道它是否值得?

我还惊讶地发现,你可以在函数声明中的形参中省略const,但可以在函数定义中包含它,例如:

. h文件

void func(int n, long l);

. cpp文件

void func(const int n, const long l)

这有什么原因吗?这对我来说有点不寻常。


当前回答

Const形参仅在通过引用(即引用或指针)传递形参时才有用。当编译器看到一个const形参时,它会确保形参中使用的变量在函数体中没有被修改。为什么会有人想让一个按值参数作为常数呢?: -)

其他回答

1. 根据我的评估,最佳答案是:

根据我的评估,@Adisak的答案是最好的答案。请注意,这个答案在某种程度上是最好的,因为除了使用合理和深思熟虑的逻辑之外,它还使用了最完善的真实代码示例。

2. 我自己的话(同意最好的答案):

For pass-by-value there is no benefit to adding const. All it does is: limit the implementer to have to make a copy every time they want to change an input param in the source code (which change would have no side effects anyway since what's passed in is already a copy since it's pass-by-value). And frequently, changing an input param which is passed by value is used to implement the function, so adding const everywhere can hinder this. and adding const unnecessarily clutters the code with consts everywhere, drawing attention away from the consts that are truly necessary to have safe code. When dealing with pointers or references, however, const is critically important when needed, and must be used, as it prevents undesired side effects with persistent changes outside the function, and therefore every single pointer or reference must use const when the param is an input only, not an output. Using const only on parameters passed by reference or pointer has the additional benefit of making it really obvious which parameters are pointers or references. It's one more thing to stick out and say "Watch out! Any param with const next to it is a reference or pointer!". What I've described above has frequently been the consensus achieved in professional software organizations I have worked in, and has been considered best practice. Sometimes even, the rule has been strict: "don't ever use const on parameters which are passed by value, but always use it on parameters passed by reference or pointer if they are inputs only."

3.谷歌的话(同意我和最好的答案):

(摘自“谷歌c++风格指南”)

对于通过value传递的函数形参,const对调用者没有影响,因此不建议在函数声明中使用。参见tow #109。

对局部变量使用const既不鼓励也不鼓励。

来源:谷歌c++风格指南的“const的使用”部分:https://google.github.io/styleguide/cppguide.html#Use_of_const。这是一个非常有价值的部分,所以请阅读整个部分。

请注意,“tow# 109”代表“本周小贴士#109:函数声明中有意义的const”,这也是一个有用的阅读。它提供了更多的信息,对要做的事情的规定性更少,并且在谷歌c++样式指南关于上面引用的const规则之前出现,但由于它提供的清晰性,上面引用的const规则被添加到谷歌c++样式指南中。

Also note that even though I'm quoting the Google C++ Style Guide here in defense of my position, it does NOT mean I always follow the guide or always recommend following the guide. Some of the things they recommend are just plain weird, such as their kDaysInAWeek-style naming convention for "Constant Names". However, it is still nonetheless useful and relevant to point out when one of the world's most successful and influential technical and software companies uses the same justification as I and others like @Adisak do to back up our viewpoints on this matter.

4. Clang的linter, Clang -tidy,有一些选项:

答:同样值得注意的是,Clang的linter, Clang -tidy,有一个选项,可读性-avoid-const-params-in-decls,描述在这里,以支持在代码库中强制不使用const的值传递函数参数:

检查函数声明的形参是否为顶级const。

声明中的Const值不会影响函数的签名,因此它们不应该放在那里。

例子:

Void f(const字符串);//错误:const是顶级的。 Void f(const string&);//好:const不是顶级的。

为了完整和清晰,我自己再举两个例子:

void f(char * const c_string);   // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]
void f(const char * c_string);   // Good: const is not top level. [This makes what is being _pointed to_ const]

B.它还有这个选项:readable -const-return-type - https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html

5. 我的务实的方法是如何在这个问题上给出一个风格指南:

我只需复制粘贴到我的风格指南中:

[复制/ START纸浆]

Always use const on function parameters passed by reference or pointer when their contents (what they point to) are intended NOT to be changed. This way, it becomes obvious when a variable passed by reference or pointer IS expected to be changed, because it will lack const. In this use case const prevents accidental side effects outside the function. It is not recommended to use const on function parameters passed by value, because const has no effect on the caller: even if the variable is changed in the function there will be no side effects outside the function. See the following resources for additional justification and insight: "Google C++ Style Guide" "Use of const" section "Tip of the Week #109: Meaningful const in Function Declarations" Adisak's Stack Overflow answer on "Use of 'const' for function parameters" "Never use top-level const [ie: const on parameters passed by value] on function parameters in declarations that are not definitions (and be careful not to copy/paste a meaningless const). It is meaningless and ignored by the compiler, it is visual noise, and it could mislead readers" (https://abseil.io/tips/109, emphasis added). The only const qualifiers that have an effect on compilation are those placed in the function definition, NOT those in a forward declaration of the function, such as in a function (method) declaration in a header file. Never use top-level const [ie: const on variables passed by value] on values returned by a function. Using const on pointers or references returned by a function is up to the implementer, as it is sometimes useful. TODO: enforce some of the above with the following clang-tidy options: https://clang.llvm.org/extra/clang-tidy/checks/readability-avoid-const-params-in-decls.html https://clang.llvm.org/extra/clang-tidy/checks/readability-const-return-type.html

下面是一些演示上述const规则的代码示例:

参数示例: (有些是从这里借来的)

void f(const std::string);   // Bad: const is top level.
void f(const std::string&);  // Good: const is not top level.

void f(char * const c_string);   // Bad: const is top level. [This makes the _pointer itself_, NOT what it points to, const]
void f(const char * c_string);   // Good: const is not top level. [This makes what is being _pointed to_ const]

示例: (有些是从这里借来的)

// BAD--do not do this:
const int foo();
const Clazz foo();
Clazz *const foo();

// OK--up to the implementer:
const int* foo();
const int& foo();
const Clazz* foo();

复制/ PASTE黑的外星人探索铝

关键词:const在函数形参中的应用;编码标准;C和c++编码标准;编码规则;最佳实践;代码标准;Const返回值

我知道这个问题“有点”过时了,但当我遇到它时,其他人可能也会在未来这样做... ...我仍然怀疑这个可怜的家伙会在这里列出我的评论:)

It seems to me that we are still too confined to C-style way of thinking. In the OOP paradigma we play around with objects, not types. Const object may be conceptually different from a non-const object, specifically in the sense of logical-const (in contrast to bitwise-const). Thus even if const correctness of function params is (perhaps) an over-carefulness in case of PODs it is not so in case of objects. If a function works with a const object it should say so. Consider the following code snippet

#include <iostream>

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
class SharedBuffer {
private:

  int fakeData;

  int const & Get_(int i) const
  {

    std::cout << "Accessing buffer element" << std::endl;
    return fakeData;

  }

public:

  int & operator[](int i)
  {

    Unique();
    return const_cast<int &>(Get_(i));

  }

  int const & operator[](int i) const
  {

    return Get_(i);

  }

  void Unique()
  {

    std::cout << "Making buffer unique (expensive operation)" << std::endl;

  }

};

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void NonConstF(SharedBuffer x)
{

  x[0] = 1;

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
void ConstF(const SharedBuffer x)
{

  int q = x[0];

}

//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
int main()
{

  SharedBuffer x;

  NonConstF(x);

  std::cout << std::endl;

  ConstF(x);

  return 0;

}

附注:你可能会认为(const)引用在这里更合适,并提供相同的行为。嗯,对的。只是给出了与我在其他地方看到的不同的画面……

你的例子中所有的const都没有目的。c++默认情况下是值传递的,因此该函数获得这些整型和布尔型的副本。即使函数修改了它们,调用者的副本也不会受到影响。

所以我会避免额外的const,因为

他们redudant 他们弄得乱七八糟 文本 他们阻止我 更改传入的值 它可能有用或有效的情况。

原因是形参的const只在函数内局部应用,因为它处理的是数据的副本。这意味着函数签名实际上是相同的。不过,经常这样做可能是不好的风格。

我个人倾向于不使用const,除了引用和指针形参。对于复制的对象来说,这并不重要,尽管它可以更安全,因为它表明了函数中的意图。这真的是一个主观判断。我倾向于使用const_iterator,但当循环某些东西时,我不打算修改它,所以我猜每个人都有自己的,只要严格维护引用类型的const正确性。

我对函数形参使用const,这些形参是引用(或指针),只是[in]数据,不会被函数修改。意思是,使用引用的目的是避免复制数据,不允许更改传递的参数。

在你的例子中,将const放在布尔b形参上只是对实现施加了约束,对类的接口没有贡献(尽管通常建议不改变形参)。

的函数签名

void foo(int a);

and

void foo(const int a);

是一样的,这就解释了你的。c和。h

Asaf