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 ofcolor
so it doesn't matter thatcolor
eventually goes out of scope.You'd have issues if the member variable
_color
was itself a reference.