【问题标题】:Behavior when dereferencing the .end() of a vector of strings取消引用字符串向量的 .end() 时的行为
【发布时间】:2014-11-17 04:38:38
【问题描述】:

我想知道将string 设置为等于通过取消引用strings 的vector 的未结束的iterator 返回的值是否“安全”。当我运行程序时

#include <vector>
#include <string>

int main()
{

    std::vector<std::string> myVec;
    std::cout << *myVec.end();
    return 0;
}

我收到以下错误。

/usr/local/lib/gcc/i686-pc-linux-gnu/4.1.2/../../../../include/c++/4.1.2/debug/safe_iterator.h:181:
    error: attempt to dereference a past-the-end iterator.

Objects involved in the operation:
iterator "this" @ 0x0xffdb6088 {
type = N11__gnu_debug14_Safe_iteratorIN9__gnu_cxx17__normal_iteratorIPSsN10__gnu_norm6vectorISsSaISsEEEEEN15__gnu_debug_def6vectorISsS6_EEEE (mutable iterator);
  state = past-the-end;
  references sequence with type `N15__gnu_debug_def6vectorISsSaISsEEE' @ 0x0xffdb6088
}

Disallowed system call: SYS_kill

您可以在http://codepad.org/fJA2yM30查看它

我想知道这一切的原因是因为我的代码中有一个类似的 sn-p

std::vector<const std::string>::iterator iter(substrings.begin()), offend(substrings.end());
while (true)
{
    this_string = *iter;
    if (_programParams.count(this_string) > 0)
    {
        this_string = *++iter;

如果++iter 等于offend,我想确保不会发生奇怪的事情。

【问题讨论】:

  • “我想确保不会发生奇怪的事情” -- 任何事情都可能发生,包括你可能称之为奇怪的事情。它取决于编译器、架构和/或标准库实现。

标签: c++


【解决方案1】:

你说:

我想知道将字符串设置为等于通过取消引用字符串向量的结束迭代器返回的字符串是否“安全”

不,这不安全。来自http://en.cppreference.com/w/cpp/container/vector/end

返回一个迭代器,指向容器最后一个元素之后的元素。

此元素充当占位符;尝试访问它会导致未定义的行为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-22
    相关资源
    最近更新 更多