gpt4 book ai didi

c++ - 为什么不能将临时对象作为 ref args 发送给 C++ 中的函数?

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

这个有效:

class Foo {};
void external_function(Foo&);
void f() {
Foo b;
external_function(b);
}

这不是:

class Foo {};
void external_function(Foo&);
void f() {
external_function(Foo());
}

clang 说:

aac.cc:3:6: note: candidate function not viable: no known conversion from 'Derived' to 'Base &' for 1st argument;

GCC 实际上更多有助于:

aac.cc:7:30: error: invalid initialisation of non-const reference of type ‘Base&’ from an rvalue of type ‘Derived’

Herb Sutter ( http://herbsutter.com/2008/01/01/gotw-88-a-candidate-for-the-most-important-const/ ) 说非常量引用不能用于右值,这在他的示例中有意义,但在我的示例中则不然,因为对象在 external_function() 调用期间存在,不是吗?

我知道如何让它发挥作用;只需创建一个命名对象,使其不是右值(就像我上面所做的那样),或者使用 const ref。但我想知道为什么它是不允许的,因为它对我来说似乎是安全的。

最佳答案

您不能将任何 类型的临时对象绑定(bind)到非常量左值引用。这里的继承只是一种干扰。

struct Foo{};

void bar(Foo&) {}
void cbar(const Foo&) {}

int main()
{
Foo f;
bar(f); // OK
bar(Foo()); // ERROR
cbar(Foo()); // OK: const reference binds to temporary
}

至于最终的“为什么?”,它只是被认为容易出错,允许通过左值引用修改右值。引自“C++ 编程语言,第四版”§7.7.1

References to variables and references to constants are distinguished because introducing a temporary for a variable would have been highly error-prone; an assignment to the variable would become an assignment to the - soon to dissappear - temporary. No such problem exists for references to constants...

关于c++ - 为什么不能将临时对象作为 ref args 发送给 C++ 中的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18250594/

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