Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ assign const reference to instance variable (memory issues?)

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?

like image 740
SPQR3 Avatar asked Feb 09 '23 21:02

SPQR3


1 Answers

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

like image 81
Bathsheba Avatar answered Feb 13 '23 02:02

Bathsheba