Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the address of the return value of a function in C++

Tags:

c++

Given this prototype which does a Endian conversion:

time_t Flip( time_t );

I would like to use the return value in a function that takes a BYTE* as an argument. Something like this:

SetBytesAt( 0, (BYTE*)&(Flip( t )) );

But this does not compile. Gives me this error "& requires l-value". If the () are removed from around the Flip function, the same error is generated.

Now, I know that I can just do this:

time_t temp_t = Flip( t );
SetBytesAt( 0, (BYTE*)&temp_t );

But it seems to me that I should be able to accomplish the same thing without the temporary temp_t variable.

like image 745
user1296467 Avatar asked Mar 27 '12 20:03

user1296467


2 Answers

Unfortunately, no. You cannot take the address of a temporary (more correctly, an r-value). That's just the way the language has been defined.

like image 113
Oliver Charlesworth Avatar answered Sep 28 '22 14:09

Oliver Charlesworth


Don't try this at home.

template <typename T>
class AddressableTemporary
{
public:

    AddressableTemporary(T const value)
        : value_(value)
    {
    }

    operator T*() { return &value_; }

private:

    T value_;
};

template <typename T>
AddressableTemporary<T> MakeAddressable(T value)
{
    return AddressableTemporary<T>(value);
}

Used as:

int  F() { return 42; }
void G(int const* const p) { std::cout << *p; }

int main()
{
    G(MakeAddressable(F()));
}

But really, don't do this. Either use a variable, or write a wrapper function that encapsulates usage of the variable, or rework your code so that you don't need to worry about this (e.g., modify the function so that it takes, say, a const reference).

like image 26
James McNellis Avatar answered Sep 28 '22 15:09

James McNellis