c++ - 取消引用字符串 vector 的 .end() 时的行为

标签 c++

我想知道将 string 设置为等于通过取消引用 vector 的尾端 iterator 返回的任何内容是否“安全” string。当我运行程序时

#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 查看它

我对这一切感到疑惑的原因是因为我的代码中有一段类似于

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,我想确保不会发生奇怪的事情。

最佳答案

你说:

I'm wondering if it's "safe" to set a string equal to whatever is returned by dereferencing the off-the-end iterator of a vector of strings

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

Returns an iterator to the element following the last element of the container.

This element acts as a placeholder; attempting to access it results in undefined behavior.

关于c++ - 取消引用字符串 vector 的 .end() 时的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965621/

相关文章:

c++ - c和c++上下文中静态、自动、全局和局部变量的区别

c++ - 递归创建 boost 属性树

c++ - 特定 type_trait vector 的类特化

c++ - 关于如何在 C++ 中处理不同项目中的文件所需的类(class)

C++ stod 函数等效

c++ - VisualStudio 和 gcc 之间 *.dll *.a *.lib *.def 的兼容性

c++ - 共享内存的强大 CRITCAL_SECTION?

C++ 多态性 : Derived class calls Base class virtual funciton instead of the overriden derived one

c# - 如何知道 Windows 中是否正在访问设备?

c++ - 多速率线程