简单的答案是
在大多数情况下
,向需要可变左值引用的函数传递临时值表示
逻辑错误
,C++语言正在尽最大努力帮助您避免出错。
函数声明:
void foo(Bar& b)
建议以下叙述:
foo引用了一个酒吧,
b
,它将修改。
乙
因此
输入和输出
传递一个临时的输出占位符
正常地
比调用返回对象的函数更糟糕的逻辑错误,只会丢弃未经检查的对象。
例如:
Bar foo();
void test()
{
/*auto x =*/ foo(); // probable logic error - discarding return value unexamined
}
但是,在这两个版本中,没有问题:
void foo(Bar&& b)
foo拥有bar引用的对象的所有权
void foo(Bar b)
FOO概念上接受一个条的副本,尽管在许多情况下编译器会决定不需要创建和复制条。
所以问题是,我们要实现什么?如果我们只需要一个酒吧,我们可以使用
Bar&& b
或
Bar b
版本。
如果我们想
也许吧
使用临时和
也许吧
使用现有的条,则可能需要两个重载
foo
,因为它们在语义上会有细微的不同:
void foo(Bar& b); // I will modify the object referenced by b
void foo(Bar&& b); // I will *steal* the object referenced by b
void foo(Bar b); // I will copy your Bar and use mine, thanks
如果我们需要这种可选性,我们可以通过将一个封装在另一个中来创建它:
void foo(Bar& b)
{
auto x = consult_some_value_in(b);
auto y = from_some_other_source();
modify_in_some_way(b, x * y);
}
void foo(Bar&& b)
{
// at this point, the caller has lost interest in b, because he passed
// an rvalue-reference. And you can't do that by accident.
// rvalues always decay into lvalues when named
// so here we're calling foo(Bar&)
foo(b);
// b is about to be 'discarded' or destroyed, depending on what happened at the call site
// so we should at lease use it first
std::cout << "the result is: " << v.to_string() << std::endl;
}
有了这些定义,这些都是合法的:
void test()
{
Bar b;
foo(b); // call foo(Bar&)
foo(Bar()); // call foo(Bar&&)
foo(std::move(b)); // call foo(Bar&&)
// at which point we know that since we moved b, we should only assign to it
// or leave it alone.
}
好吧,为什么这么在乎?为什么修改一个没有意义的临时文件是一个逻辑错误?
好吧,想象一下:
Bar& foo(Bar& b)
{
modify(b);
return b;
}
我们期待着做这样的事情:
extern void baz(Bar& b);
Bar b;
baz(foo(b));
现在假设这可以编译:
auto& br = foo(Bar());
baz(br); // BOOM! br is now a dangling reference. The Bar no longer exists
因为我们被迫在一个特殊的超负荷
福
作者
福
可以确信这个错误不会在您的代码中发生。