pass by reference c++

2020-08-18 02:59发布

My teacher in c++ told me that call by reference should only be used if I'm not going to change anything on the arrays inside the function. I have some really big vectors that I'm passing around in my program. All the vectors will be modified inside the functions. My matrices are of sizes about [256*256][256][50]...

Is there some particular reason not to use call-by reference here?

AFAIK call by reference should be way faster and consume less memory?

11条回答
成全新的幸福
2楼-- · 2020-08-18 03:14

Your teacher is wrong. If you need to modify arrays, pass by reference is the way to go. If you don't want something modified, pass by const reference.

查看更多
倾城 Initia
3楼-- · 2020-08-18 03:20

My teacher in c++ told me that call by reference should only be used if I'm not going to change anything on the arrays inside the function.

It should be used when you are not changing something inside the function or you change things and want the changes to be reflected to the original array or don't care about the changes to be reflected in the original array.

It shouldn't be used if you don't want your function to change your original array (you need to preserve the original values after the call) and the callee function changes the values of the passed argument.

查看更多
女痞
4楼-- · 2020-08-18 03:23

You can pass by reference if:

  1. you won't modify passed object
  2. you want to modify object and don't want to keep old object untouched

When you pass something by reference, then only pointer is passed to function. If you pass whole object then you need to copy it, so it will consume more cpu and memory.

查看更多
霸刀☆藐视天下
5楼-- · 2020-08-18 03:23

Usually, in introductory courses, they tell you that so you don't accidentally change something you didn't want to.

Like if you passed in userName by reference, and accidentally changed it to mrsbuxley that probably would cause errors, or at the very least be confusing later on.

查看更多
做自己的国王
6楼-- · 2020-08-18 03:32

Generally speaking, objects should always be passed by reference. Otherwise a copy of the object will be generated and if the object is substantially big, this will affect performance.

Now if the method or function you are calling does not modify the object, it is a good idea to declare the function as follows:

void some_function(const some_object& o);

This will generate a compile error if you attempt to modify the object's state inside the function body.

Also it should be noted that arrays are always passed by reference.

查看更多
叼着烟拽天下
7楼-- · 2020-08-18 03:32

Our house style is to NEVER pass an object by value but to always pass a reference or const reference. Not only do we have data structures that can contain 100s of MB of data and pass by value would be an application killer, but also if we were passing 3D points and vectors by value the our applications would grind to a halt.

查看更多
登录 后发表回答