何时使用函数参数const和const引用 [英] when to use const and const reference in function args

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

问题描述

在写有正在传递给它,从我的理解常量应始终使用,如果你能guarantuee该对象将不会改变或一个const指针,若指针不会改变ARGS一个C ++函数。

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.

时,这种做法建议当别的吗?

When else is this practice advised?

当你使用const引用,什么是经过短短使其通过指针,例如优势?

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

这个是什么无效为MyObject :: Somefunc(常量的std :: string的&安培; myString的)将是什么点有一个常量字符串,如果一个字符串其实已经不可变对象?

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);

此情况下,主要是关于风格:你想调用看起来像调用(OBJ)通话(放大器; OBJ)?但是,存在的差别事项两点。如果您希望能够通过空,你必须使用一个指针。如果你正在运算符重载,你不能用一个指针来代替。

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);

这是有趣的案例。经验法则是廉价复制类型是按值传递 - 这通常是小类型(但不总是) - 有的则是由常量REF通过。但是,如果你需要你的函数内的复制,无论你应该通过按值。 (是的,这暴露了位实现细节。花莲乐C ++。的)

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);

这些声明实际上是的完全一样的功能!的当值传递,常量纯粹是一个实现细节。 试试看:

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

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

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