gpt4 book ai didi

c++ - 如何在没有临时变量的情况下传递指向整数的指针?

转载 作者:太空狗 更新时间:2023-10-29 21:10:03 28 4
gpt4 key购买 nike

在我过去的许多语言中,有一种方法可以将整数常量/文字作为引用传递,以避免为函数创建不必要的极短生命周期变量。一个很好的例子是 setsockopt 调用的重用变量。例如

int reuseVal = 1;    
setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &reuseVal, sizeof (reuseVal));

某些语言允许您执行以下操作

setsockopt(s, SOL_SOCKET, SO_REUSEADDR, %ref(1), sizeof (int));

在 C++ 中是否有类似的方法可用?

最佳答案

C++ 中没有内置的东西可以满足您的需求,但您自己构建一个很容易(为了清晰起见,需要额外的日志记录):

template <typename T>
class holster
{
public:
using value_type = T;

template <typename... U>
holster(U&&... args)
: _val(std::forward<U>(args)...)
{
std::cout << "CTOR: holster" << std::endl;
}

~holster()
{
std::cout << "DTOR: holster" << std::endl;
}

value_type* ptr() { return &_val; }

private:
value_type _val;
};

这种类型的用法相当简单:

struct thing
{
thing()
{
std::cout << "CTOR: thing" << std::endl;
}

~thing()
{
std::cout << "DTOR: thing" << std::endl;
}
};

void foo(thing*)
{
std::cout << "in foo" << std::endl;
}

int main()
{
foo(holster<thing>().ptr());
return 0;
}

扩展回原来的例子:

setsockopt(s, SOL_SOCKET, SO_REUSEADDR, holster<int>(1).ptr(), sizeof (int));

为什么会这样? C++ 生命周期的一个鲜为人知的特性是,任何为传递给函数而创建的临时对象都会在函数的持续时间内延长生命周期。所指对象 (holster::_val) 保证继续存在直到 foo 返回,并且在下一个完整表达式被评估之前将被正确销毁(在本例中,在 ; 之前)。

§6.6.7/4 [class.temporary]

When an implementation introduces a temporary object of a class that has a non-trivial constructor ([class.default.ctor], [class.copy.ctor]), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor ([class.dtor]). Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

关于c++ - 如何在没有临时变量的情况下传递指向整数的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56014873/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com