在C ++ 11中,如何获取没有名称的临时左值? [英] In C++11, how can I get a temporary lvalue without a name?

查看:162
本文介绍了在C ++ 11中,如何获取没有名称的临时左值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个传统的C库和一个函数( setsockopts )想要一个参数的指针。在C ++ 11(gcc 4.8)中,我可以传递这个参数而不初始化一个命名的变量?

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
}


推荐答案

我只是创建一个包装器 setsockopt 如果这是一个麻烦(未测试)

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);

这篇关于在C ++ 11中,如何获取没有名称的临时左值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆