Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Taking address of rvalue warning

I am trying to pass in the memory address of the mpuTest class property to the fsVar.initialize() method, but I get this error:

main.cpp:38:42: error: taking address of rvalue [-fpermissive]
   38 |     fsVar.initialize(&test3Var.getMpuTest());

I have done a little reading and have learned that an rvalue is something that may not have storage or memory associated with it, like a simple integer. I also know that an lvalue is something that is stored in memory with an address, like a variable.

But I have noticed with the below code that if I have a getter in a class for a property of that class, and I try and use that return value’s memory address with &, it will give me the above error. If you don’t understand this example please view the below code example.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <iostream>

using namespace std;

class mpu {
public:
    void printSomething() {
        cout << "Hi" << endl;
    }
};

class fs {
private:
    mpu* t1;
public:
    void initialize(mpu *mpuPtr) {
        this->t1 = mpuPtr;
    }
    
    void printSomething2() {
        this->t1->printSomething();
    }
};

class Test3 {
private:
    mpu mpuTest;
public:
    mpu getMpuTest() {
        return mpuTest;
    }
};

int main()
{
    Test3 test3Var;
    fs fsVar;
    fsVar.initialize(&test3Var.getMpuTest());
    fsVar.printSomething2();
    return 0;
}

>Solution :

The reason why you are getting this error is because test3Var.getMpuTest() is is returning by value, not by reference. When you return an object by value, a temporary – an rvalue – copy of the object is created. Hence the error message talks about rvalue:

main.cpp:38:42: error: taking address of rvalue [-fpermissive]
   38 |     fsVar.initialize(&test3Var.getMpuTest());

The & operator in C++ is only valid for lvalues – objects that have a memory location, not for rvalues (temporary objects), which is why the compiler is giving you this error.

Solution is to return by reference:

mpu& getMpuTest() {
    return mpuTest;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading