Safe some memory when passing and assigning

58 views Asked by At

I am new to C++ (coming from C#) and I want to get that memory stuff right from the beginning.
In the following snipped a variable of type WorldChunkCoordinates is passed by value to the inline constructor of WorldChunk and then the passed Coordinates are assigned to WorldChunk::Coordinates, which I believe is a copy operation as well.
(copy-assignment operation?)

If my assumptions are correct then this would be kinda stupid, because I copy the instance twice. I think it would be much more performant if I would pass by value and assign by reference pointer. But WorldChunk::Coordinates is not a pointer neither a reference.

WorldChunk(WorldChunkCoordinates Coordinates) {
   WorldChunk::Coordinates = Coordinates;
}

Is there a way to safe my programm from copying the instance twice?
If so, how?

Also: Is assigning by = always a copy operation by default?
And: How should I know that a specific class may have another copy assignment operation that copies by reference?

3

There are 3 answers

8
nwp On BEST ANSWER

Its a known and solved problem, called initializer list (not to be confused with the container). Looks like

 WorldChunk(WorldChunkCoordinates Coordinates) : Coordinates(Coordinates){} 

Consider using lower case letters for variable names.

You could also use

 WorldChunk(const WorldChunkCoordinates &Coordinates) : Coordinates(Coordinates){} 

but it is not obvious that dereferencing is faster than copying, especially when taking compiler optimizations into account.

1
AF_cpp On

first of all a simple solutuion:

change your method to:

WorldChunk(const WorldChunkCoordinates& Coordinates) {  WorldChunk::Coordinates = Coordinates;}

This will lead to a single assignment instruction because coordinates is a reference.

The default constructed assignment operator assigns memberwise. The parameter of the assignment operator is (usually) a const reference to the object so that you don't copy the parameter.

By the way a little tutorial: http://www.cplusplus.com/doc/tutorial/ which is very good in my point of view.

0
KABoissonneault On

The convention in C++ for user type function arguments is to pass by const reference (const MyType&) for input arguments, and by reference for in-out arguments (MyType&).