Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: Pass Vector struct by reference or value?

This is my Vector struct: struct Vector{ float x, y; };

  • Should I pass it to functions by value or as const Vector&?
like image 676
jarhead Avatar asked Mar 12 '11 17:03

jarhead


2 Answers

If you pass by value, the function will get a copy that it can modify locally without affecting the caller.

If you pass by const-reference, the function will only get a read-only reference. No copying involved, but the called function cannot modify it locally.

Given the size of the struct, the copy overhead will be very small. So choose what is best/easiest for the called function.

like image 54
Mat Avatar answered Oct 23 '22 23:10

Mat


For such a small structure, either one may be the most efficient, depending on your platform and compiler.

(The name may be a bit confusing to other programmers, since vector in C++ usually means "dynamic array". How's about Vector2D?)

like image 22
Fred Foo Avatar answered Oct 23 '22 23:10

Fred Foo