我有一个传统的 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/