I always thought that references were functionally the same as pointers, they just have a much friendlier syntax, and some other minor differences ( references cannot be assigned to null, they cannot be reassigned).
But today I saw this code and I do not understand why it is correct:
There is simple struct, Color3B. We create one on the stack like this:
Color3B color(255,0,0);
There is another class, one of its instance variables is of Color3B type.
class Node{
private:
Color3B _color;
public:
void setColor(const Color3B& color){
_color = color;
}
};
Usage:
void someFunction(){
Color3B color(255,0,0);
_someNode->setColor(color);
}
I think color is destroyed when it is out of scope: when someFunction ends. But setColor gets a memory address of something created on the stack, and stores it. But there are no issues, when I access Node's _color, it is always there and has a correct value.
What am I missing here?
_color = color;
takes a value copy of color
so it doesn't matter that color
eventually goes out of scope.
You'd have issues if the member variable _color
was itself a reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With