简体   繁体   中英

Pointer to rvalue object member variable

This is a very quick question. I have the following code:

struct integer {
    int x;
    int& ref() {
        return x;
    }
};

//main...
int* l = &integer{4}.ref();
std::cout << *l;

My question is: Isn't &integer{4}.ref() a rvalue since it is a temporary object? How can I have a pointer to it? And is it undefined behavior?

While integer{4} is an rvalue, you call ref() which returns an int& which is always an lvalue. This allows the code to compile, but you have undefined behavior since you dereference a pointer to an object that no longer exists.

To fix this you can provide a ref-qualifer for ref which only allows it to be called on lvalues. That would look like

struct integer {
    int x;
    int& ref() & {
        return x;
    }
};

and will cause a compiler error if you try to use

integer{4}.ref()

since integer{4} is not an lvalue which ref now requires.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM