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?
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.