何时在函数args中使用const和const引用?

Ton*_*ion 22 c++ arguments const

在编写一个带有传递给它的args的C++函数时,如果可以保证不改变对象,则应始终使用const,如果指针不会被更改,则应始终使用const指针.

这种做法何时建议?

你什么时候使用const引用,比仅通过指针传递它有什么好处?

那么void MyObject::Somefunc(const std::string& mystring) 如果一个字符串实际上已经是一个不可变对象,那么拥有一个const字符串会有什么意义呢?

小智 40

Asking whether to add const is the wrong question, unfortunately.

Compare non-const ref to passing a non-const pointer

void modifies(T &param);
void modifies(T *param);
Run Code Online (Sandbox Code Playgroud)

This case is mostly about style: do you want the call to look like call(obj) or call(&obj)? However, there are two points where the difference matters. If you want to be able to pass null, you must use a pointer. And if you're overloading operators, you cannot use a pointer instead.

Compare const ref to by value

void doesnt_modify(T const &param);
void doesnt_modify(T param);
Run Code Online (Sandbox Code Playgroud)

This is the interesting case. The rule of thumb is "cheap to copy" types are passed by value — these are generally small types (but not always) — while others are passed by const ref. However, if you need to make a copy within your function regardless, you should pass by value. (Yes, this exposes a bit of implementation detail. C'est le C++.)

Compare const pointer to non-modifying plus overload

void optional(T const *param=0);
// vs
void optional();
void optional(T const &param); // or optional(T param)
Run Code Online (Sandbox Code Playgroud)

This is related to the non-modifying case above, except passing the parameter is optional. There's the least difference here between all three situations, so choose whichever makes your life easiest. Of course, the default value for the non-const pointer is up to you.

Const by value is an implementation detail

void f(T);
void f(T const);
Run Code Online (Sandbox Code Playgroud)

这些声明实际上是完全相同的功能! 当传递值时,const纯粹是一个实现细节. 试试看:

void f(int);
void f(int const) {/*implements above function, not an overload*/}

typedef void C(int const);
typedef void NC(int);
NC *nc = &f;  // nc is a function pointer
C *c = nc;  // C and NC are identical types
Run Code Online (Sandbox Code Playgroud)

  • C++指针*是*空对象模式. (4认同)

Bjö*_*lex 6

一般规则是,const尽可能使用,并且仅在必要时省略它。const可能使编译器能够优化并帮助您的同行了解您的代码打算如何使用(并且编译器会发现可能的误用)。

至于你的例子,字符串在 C++ 中不是一成不变的。如果您const将一个字符串的非引用传递给一个函数,该函数可能会修改它。C++ 没有内置于语言中的不变性概念,您只能使用封装和const(尽管永远不会防弹)来模拟它。

在思考@Eamons 评论并阅读一些内容后,我同意优化不是使用const. 主要原因是有正确的代码。

  • 我不认为编译器实际上可以基于 const 注释优化任何东西——const 并不意味着不变性,只是在这个范围内缺乏改变的意图。 (2认同)