何时在函数args中使用const和const引用? [英] When to use const and const reference in function args?

查看:113
本文介绍了何时在函数args中使用const和const引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在编写具有传递给它的args的C ++函数时,根据我的理解,如果可以保证不更改对象或不更改指针,则应始终使用const或const指针.

When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be changed or a const pointer if the pointer won't be changed.

还有什么建议?

什么时候使用const引用,与仅将其传递给指针相比,有什么好处?

When would you use a const reference and what are the advantages over just passing it through a pointer for example?

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

What about this void MyObject::Somefunc(const std::string& mystring) What would be the point in having a const string if a string is in fact already an immutable object?

推荐答案

不幸的是,询问是否添加const是错误的问题.

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

void modifies(T &param);
void modifies(T *param);

这种情况主要与样式有关:您是否希望呼叫看起来像call(obj)call(&obj)?但是,在两点上,差异很重要.如果希望能够传递null,则必须使用指针.而且,如果要重载运算符,则不能使用指针.

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.

void doesnt_modify(T const &param);
void doesnt_modify(T param);

这是一个有趣的情况.经验法则是廉价复制"类型通过值传递-这些类型通常是小类型(但并非总是如此),而其他类型则通过const ref传递.但是,如果无论如何都需要在函数中进行复制,则

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++.)

void optional(T const *param=0);
// vs
void optional();
void optional(T const &param); // or optional(T param)

这与上面的非修改情况有关,但传递参数是可选的.这三种情况之间的差异最小,因此请选择使您的生活最轻松的一种.当然,非const指针的默认值取决于您.

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.

void f(T);
void f(T const);

这些声明实际上是完全相同的函数!当按值传递时,const纯粹是实现细节. 尝试一下:

These declarations are actually the exact same function! When passing by value, const is purely an implementation detail. Try it out:

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

这篇关于何时在函数args中使用const和const引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆