Why is it illegal to take the address of an rvalue temporary?

前端 未结 6 1874
甜味超标
甜味超标 2020-11-27 05:34

According to \" How to get around the warning "rvalue used as lvalue"? \", Visual Studio will merely warn on code such as this:

int bar() {
   retu         


        
6条回答
  •  孤独总比滥情好
    2020-11-27 06:05

    Certainly temporaries have storage. You could do something like this:

    template
    const T *get_temporary_address(const T &x) {
        return &x;
    }
    
    int bar() { return 42; }
    
    int main() {
        std::cout << (const void *)get_temporary_address(bar()) << std::endl;
    }
    

    In C++11, you can do this with non-const rvalue references too:

    template
    T *get_temporary_address(T &&x) {
        return &x;
    }
    
    int bar() { return 42; }
    
    int main() {
        std::cout << (const void *)get_temporary_address(bar()) << std::endl;
    }
    

    Note, of course, that dereferencing the pointer in question (outside of get_temporary_address itself) is a very bad idea; the temporary only lives to the end of the full expression, and so having a pointer to it escape the expression is almost always a recipe for disaster.

    Further, note that no compiler is ever required to reject an invalid program. The C and C++ standards merely call for diagnostics (ie, an error or warning), upon which the compiler may reject the program, or it may compile a program, with undefined behavior at runtime. If you would like your compiler to strictly reject programs which produce diagnostics, configure it to convert warnings to errors.

提交回复
热议问题