c++ - 在 C++11 中,如何获取没有名称的临时左值?

标签 c++ c++11 lvalue

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

我有以下不满意的解决方案:

#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 创建一个包装器

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++ - 在 C++11 中,如何获取没有名称的临时左值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23566857/

相关文章:

c - 有效类型限定符有哪些规则?

c++ - 将 uint64_t 除以 numeric_limits<uint64_t>::max() 为浮点表示形式

c++ - 如何知道焦点窗口的名称/ID

c++ - std::async、std::function 对象和带有 'callable' 参数的模板

c++ - 在 C++17 中,为什么类模板与函数模板的指针类型推导明显不一致?

c - 尝试递增数组时出现 "lvalue required"错误

c++ - QtCreator qmake 无法运行编译器 'cl'

C++:在字符串中查找一个字符,然后在前一个字符之后查找另一个字符

C++11 线程 : notify_all() or notify_one() when I only have one?

C++ lambda 参数列表