我需要一些关于何时分配或列出初始化auto
类型命名变量的保证,
- A a
std::move
()ed 返回对变量的引用 - B 对变量的返回引用
在表达式之后,原点超出范围,是 A 安全 / B 不安全。示例代码:
#include <iostream>
#include <string>
#include <deque>
#include <utility>
int main() {
std::deque<std::string> container {"foo"};
auto elementB = container.front(); //B I assume this is unsafe
auto elementA = std::move(container.front());//A I assume this is safe
container.pop_front();
std::cout << "A: " << elementA << " B: " << elementB << "\n";
}
据我了解,表达式 B 生成赋值的左值权利,因此类型elementB
是左值引用,也就是左值引用std::string&
,因此不安全。
执行代码时“A:foo B:”的输出也表明了这一点。( https://ideone.com/wKKbdK ) 更新:对不起,我忘了我移动了它,所以我改变了顺序,现在输出是例外,对不起。
然而,我不确定的更麻烦的事情是表达式 A:在std::move
我假设我得到一个 xvalue 之后,它既是右值又是左值,所以我不确定对于elementA
.
因为从左值我几乎可以确定它的 UB,而左值是左值,而 xvalue 是其中的一部分,那么类型将elementA
是std::string&&
,这不安全吗?(除非 const&& AFAIK 例外)
所以总结一下:elementA 的使用是安全的标准化行为吗?它的类型是什么?