gpt4 book ai didi

c++ - 在异常情况下将临时对象绑定(bind)到非常量引用

转载 作者:搜寻专家 更新时间:2023-10-31 01:42:28 25 4
gpt4 key购买 nike

我一直读到,在函数调用的情况下,临时对象只允许绑定(bind)非常量引用参数。

案例 1:-

例如:-

class Simple{
public:
int i;
Simple(Simple &f)
{
i = f.i + 1;
}
Simple(int j)
{
i = j;
}
};

int main()
{
Simple f1 = Simple(2); // error no matching call fruit::fruit(fruit)...
return 0;
}

这会给我错误,因为我试图用非常量引用参数绑定(bind)临时值。

案例 2:-

try
{
throw e;
}
catch ( exception& e )
{
}

我了解到,当我们抛出异常时,真正传递给 catch 的是原始抛出异常的拷贝,即为抛出的对象创建一个临时对象,然后将其传递给 catch 子句。

catch 所做的是通过非 const 引用捕获此异常。这与我在案例 1 中展示的内容形成对比。

所以,我的问题是:-

1) 是否存在允许将临时绑定(bind)到非常量引用的特定场景。

2) 如果有,那么在允许这些异常(exception)时考虑了哪些因素。

最佳答案

Are there specific scenarios where binding temporary to non-const reference is allowed.

对于左值引用(即 T& 类型)没有。您不能将临时变量绑定(bind)到非常量左值引用,因为修改例如 42 这样的文字没有多大意义。它们可以绑定(bind)到 const 左值引用,因为这样就 promise 不会修改引用绑定(bind)到的对象。

它们实际上可以绑定(bind)到 rvalue-references (T&&),但这与本主题无关。

If there are then what factors are taken into account while allowing these exceptions.

临时对象确实不能绑定(bind)到非常量左值引用,但是对于异常对象有一定的规定:

取自 C++11 标准(最接近的草案 n3337 ):

§15.1/3 A throw-expression initializes a temporary object, called the exception object, the type of which is determined by removing any top-level cv-qualifiers from the static type of the operand of throw and adjusting the type from “array of T” or “function returning T” to “pointer to T” or “pointer to function returning T”, respectively. The temporary is an lvalue and is used to initialize the variable named in the matching handler (15.3). [..]

强调我的

cppreference将其简化为:

Unlike other temporary objects, the exception object is considered to be an lvalue argument when initializing the catch clause parameters, so it can be caught by lvalue reference, modified, and rethrown.

因此对于这种情况,您实际上可以将异常绑定(bind)到非常量左值引用。

关于c++ - 在异常情况下将临时对象绑定(bind)到非常量引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806857/

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