PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] What happens if I pass a temporary reference and store it as a class member?

 July 06, 2022     arduino, arduino-c++, c++, constructor, pass-by-reference     No comments   

Issue

I have a class that stores a reference to some kind of application state, which it then mutates during operation:

class Mutator {
    private:
        State& _state;

    public:
        Mutator(State& state);
        ...
};

Mutator::Mutator(State& state) : _state(state) {

}
...

Normally I would create and pass the state like this:

State state;
Mutator mutator(state);

What would happen to the state reference in my Mutator class, if I initialize the Mutator like this:

Mutator mutator(State());

I assume, since the state reference is temporary, the Mutator._state member will point to a memory location which may or may not contain the state value which leads to unpredictable behaviour. Is this correct?


Solution

If you use a reference, then the variable needs to be initialized (as not being NULL) in the constructor. This is safer, since you are assured the reference is really pointing to an existing object.

About

Mutator mutator(State());

This does not make much sense, unless the State object is used only as input for the Mutator constructor; however if it changes the newly created State variable, when the constructor returns and mutator is created, the State() instance is deleted.

Also (see note of NathanOliver below), it is not legal C++ code and not portable.

Update

Test application:

class State {
    public: State() {}
};

class Mutator {
    private:  State& _state;
    public:   Mutator(State& state) : _state(state)  { }
};

void setup() {
    Mutator mutator(State());
}

int main() {
    return 0;
}

The code above compiler and links correctly on an Arduino compiler (1.8.9):

Sketch uses 260 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 0 bytes (0%) of dynamic memory, leaving 8192 bytes for local variables. Maximum is 8192 bytes.


Answered By - Michel Keijzers
Answer Checked By - Willingham (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing