#question about pointers

1 messages · Page 1 of 1 (latest)

gilded tendon
#

does assigning them here makes them change pointers?
could you expand on this part? What do you mean exactly?

upbeat quail
#

I assume the answer you're looking for is contained within whether self.previous_chunk_pos and self.current_chunk_position are pointers or structs themselves.

if you're passing by value, then yes, copying does happen in both lines. the first will copy the data from current_chunk_pos into previous_chunk_pos. and the second line would create an all new struct to be copied into current. (the compiler may? optimize this away so its constructed in place? im not sure) either way, the real data within the struct is copied.

if you're passing by reference using pointers, then the story is a bit different. we're still "copying" the data. but now the data is simply a memory address, as opposed to the structs containing vectors. this way, between lines 1 and 2, mutating the data within previous_chunk_pos will be reflected in current_chunk_pos. this of course is no longer true once we get past the second line which overwrites current.

upbeat quail
#

yeah so, then whatever struct your self is, has space in it for two instances of that vector-containing struct. as such, when you set previous = current, you are copying the data.

#

so, &self.previous_chunk_pos != &self.current_chunk_pos

upbeat quail
#

if you are working directly with structs, there are no pointers in the first place.
what is the type of self.current_chunk_pos?

#

sure, thats fine. as long as its current_chunk_pos: MyStruct and not current_chunk_pos: *MyStruct.
The former means that it is not a pointer, and the whole data of MyStruct is contained within your self.

upbeat quail
old gyro
#

Ultimately, it's the same deal regardless of what type of thing it is.
Values are copied.

var x: u32 = 0;
var y = x; // copy of x

This is true for literally everything, even pointers.
Pointers are just integers, and y = x will mean that y is a pointer, which points to the same thing that x does; i.e: both will point to the same location in memory.

#

In the same way that y = x when they're u32s mean that they both will hold the same numeric value.