Getting rvalue address

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 does not work with GCC 4.6, while it used to work in the previous version.

Now it says: accepts an xvalue (rvalue reference) address.

Is there a way to safely pass an rvalue to another function?

+3


source to share


3 answers


: is it anyway safe to pass an rvalue reference (aka temporary address) to another function without boring storing it in a variable just for that?

Yes, there is, as in the following 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) );
}

      

+3


source


The r value does not have to be an address. However, there is a way to get the effect you want using the fact that binding the value of r to a reference makes it temporary (which has an address):

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

      

Internally, this function v

is an lvalue (despite being declared as T&&

), so its address can be accepted. You can use this function like this:



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 lifetime ends at the end of the full expression (the expression print(...)

in this case), so you need to be careful that the pointer is not used after that point.

+2


source


If you don't need to print only rvalues, you can use the standard 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;
} 

      

+1


source







All Articles