【发布时间】:2016-05-31 04:38:13
【问题描述】:
当我运行以下代码时:
std::string myString = "I'm a string.";
const std::string::iterator &myIterator = ++myString.begin();
char c = *myIterator;
std::cout << c << std::endl;
我遇到了分段错误(使用 O3 优化进行编译)。我认为这是因为++ 运算符返回std::string::iterator & 而不是std::string::iterator,所以我们得到一个临时引用。是否有理由不执行此操作以导致编译错误?即,为什么不是下面的签名?
std::string::iterator &std::string::iterator::operator++() &;
或者更好的是,为什么规范不需要以下签名以便我们可以毫无问题地处理右值?
std::string::iterator &std::string::iterator::operator++() &;
std::string::iterator std::string::iterator::operator++() &&;
【问题讨论】:
-
Cannot reproduce。你确定是因为那些线吗?附带说明,即使
++返回引用,myIterator也不是引用,因此它会复制值 -
这工作正常。你能发布完整的代码吗?
-
我同意包含这些重载会避免错误...但是对整个标准库始终如一地这样做将是一场噩梦,并且可能还会对现有代码进行重大更改。在声明 const 引用时,您可能会坚持记住要小心(而且,没有任何理由对迭代器使用 const 引用 - 它们被设计为轻量级并按值传递)。
-
IMO 首先允许
++用于纯右值有点可疑,内置 ++ 只能用于左值。但很多人似乎对此很满意。 -
事实上,这是关于这段代码是否可以编译的实现细节:一个库可以使用
char *作为字符串迭代器。
标签: c++ operators std rvalue temporary-objects