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

标签 c++ temporary

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

相关文章:

c++ - 在 C++ 中使用标准串行调度队列?

c++ - DefWindowProc() 问题

c++ - 我如何能够在 C++ 中声明一个在运行时确定的可变长度数组?

c++ - boost::function 参数定义不起作用

Fortran 运行时警告 : temporary array

git - 暂时将工作副本切换到特定的 Git 提交

mysql - 选择临时表中具有最大值的所有行

c++ - 如何检测一个容器是否保证有序列存储

C++ 函数返回一个右值,但可以分配一个新值?

rust - 为什么我不能调用具有临时值的方法?