Fsanna
Fsanna

Reputation: 377

Reference changes value when used to create object

I'm getting some strange error while running some C++ code that uses references. Basically I have three classes, the first contains an object of the second one while the second contains a vector of objects of the third class. This is the example code:

class MainClass {

public:
    SecondaryClass myClass;

private:
    void myFunction() {
        int temp = 0;
        const int& newValue = myClass.getFinalClassByIndex(temp).getInt();
        // I add another FinalClass with the same value
        myClass.addClassToVector(newValue);
        // I try to add another one but the variabile "newValue" has another value
        myClass.addClassToVector(newValue);
    }

};

class SecondaryClass {

public:
    SecondaryClass() {
        myVector.push_back(FinalClass(0));
    }

private:
    std::vector<FinalClass> myVector;

    void addClassToVector(const int& value) {
        myVector.push_back(FinalClass(value));
    }

    FinalClass& getFinalClassByIndex(const int& index) {
        return myVector.at(index);
    }

};

class FinalClass {

public:
    FinalClass(const int& value) : myInt(value){}
    FinalClass(const int&& value) : myInt(value){}

    const int& getInt(){ return myInt; }

private:
    int myInt;

};

This is what happens when I run "myFunction": I get the integer value from the first object in the vector myVector and I put it in the newValue variable. Then I try to create two new FinalClass objects with the addClassToVector method, and these two will have the same integer value as the first one.
The first new object (that will be the second object in the vector) is created correctly; when I try to create the second object (the third one in the vector) the newValue variable does not have the value 0 as it should be, but it has a totally different one. It seems like the value has been moved instead of copied into the new class.
The second constructor in the class FinalClass is used when I create the class like ' FinalClass(0) ', it gives me an error if I don't use the "&&" notation. What could the problem be in this case? I think it has something to do with the way I handle the references, but I don't understand why.

Upvotes: 1

Views: 56

Answers (1)

Radosław Cybulski
Radosław Cybulski

Reputation: 2992

You return everything by reference. Which is fine until your vector needs to be resized, which reallocates your vector's memory and invalidates all references to that memory. Including your newValue reference. As a result your const int& newValue points to memory, which contains random data and it's a miracle your program doesn't crash at all.

Stop using references when you don't need them:

newValue = myClass.getFinalClassByIndex(temp).getInt();

and

int getInt(){ return myInt; }

even better:

auto getInt(){ return myInt; }

Upvotes: 2

Related Questions