Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++11, how can I get a temporary lvalue without a name?

Tags:

c++

c++11

lvalue

I have a traditional C lib and a function (setsockopts) wants an argument by pointer. In C++11 (gcc 4.8), can I pass this argument without initializing a named variable?

I have the following, non-satisfying solution:

#include <iostream>
#include <memory>

int deref(int const * p) {return * p;}

using namespace std;

int main() {
    int arg = 0; cout << deref(& arg) << endl;
    // works, but is ugly (unnecessary identifier)

    cout << deref(& 42) << endl;
    // error: lvalue required as unary ‘&’ operand

    cout << deref(& * unique_ptr<int>(new int(42))) << endl;
    // works, but looks ugly and allocates on heap
}
like image 961
not-a-user Avatar asked May 09 '14 14:05

not-a-user


2 Answers

I'd just create a wrapper to setsockopt if that's really a trouble (not tested)

template <typename T>
int setsockopt(int socket, int level, int optname, const T& value) {
    return setsockopt(socket, level, optname, &value, sizeof(value));
}

...

setsockopt(socket, IPPROTO_TCP, TCP_NODELAY, 1);
like image 53
kennytm Avatar answered Sep 21 '22 13:09

kennytm


Write a function template to convert rvalues to lvalues:

template<typename T>
T &as_lvalue(T &&val) {
    return val;
}

Now, use it:

deref(&as_lvalue(42));

Warning: this doesn't extend the lifetime of the temporary, so you mustn't use the returned reference after the end of the full-expression in which the temporary was created.

like image 37
Mankarse Avatar answered Sep 21 '22 13:09

Mankarse