Getting the address of an rvalue

末鹿安然 提交于 2019-12-12 13:48:28

问题


class MyClass {
    public: MyClass(int a) : a(a) { }
    int a;
};

#include <iostream>
void print(MyClass* a) { std::cout << a->a << std::endl; }

int main() {
    print(&static_cast<MyClass&&>(MyClass(1337)));
    return 0;
}

This doesn't work with GCC 4.6, while it used to work in a previous version.

Now it says: taking address of xvalue (rvalue reference).

Is there any way to securely pass the address of an rvalue to another function?


回答1:


is: there is anyway to securely pass an rvalue reference (a.k.a. address of temporary) to another function without boringly storing it in a variable just to do that?

Yes, there is, like in the next example :

#include <iostream>

class MyClass {
       public: MyClass(int a) : a(a) { }
       int a;
   };


void print(MyClass&& a) { std::cout << a.a << std::endl; }

int main() {
    print( MyClass(1337) );
}



回答2:


An rvalue does not necessarily have an address. However, there is a way to get the effect you want, by exploiting the fact that binding an rvalue to a reference forces it to be a temporary (which does have an address):

template<typename T> T *addressOfTemporary(T &&v) { return &v; }

Inside this function, v is an lvalue (despite being declared as T&&), so can have its address taken. You can use this function as follows:

class MyClass {
    public: MyClass(int a) : a(a) { }
    int a;
};

#include <iostream>
void print(MyClass* a) { std::cout << a->a << std::endl; }

int main() {
    print(addressOfTemporary(MyClass(1337)));
    return 0;
}

Note that the temporary's lifetime ends at the end of the full-expression (the print(...) expression, in this case), so you will need to be careful that the pointer is not used past that point.




回答3:


If you don't particualrly need to print rvalues only, you can use a standard const reference instead:

class MyClass {
     public: MyClass(int a) : a(a) { }
     int a; 
};  

#include <iostream> 

void print(const MyClass& a) 
{ std::cout << a.a << std::endl; }  

int main() {
     print(MyClass(1337));
     return 0;
} 


来源:https://stackoverflow.com/questions/9786216/getting-the-address-of-an-rvalue

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!