使用std :: vector的奇怪分段错误

rra*_*alf 0 c++ stl segmentation-fault

看看这个片段:

#include <string>
#include <iostream>
#include <vector>

using namespace std;

class base {
public:
  string foo;
  base() {};
  base(const base &orig) {
    this->foo = orig.foo;
  };
 ~base() {} ;
};

class derived : public base {
public:
  string bar;
  derived(const derived &orig) : base(orig) {
    this->bar = orig.bar;
  }
  derived() : base() {} ;
  ~derived() {};
};

void asd(derived d)
{
    // works fine
    cout << d.foo << d.bar << endl;
}

int main(void)
{
    vector<derived> v;

    derived bla;

    bla.foo = "Test ";
    bla.bar = "String ";

    v.push_back(bla);

    asd(bla);

    // Why the hell does v.end()->foo and v.end()->bar segfault?!
    cout << v.end()->foo;
    cout << v.end()->bar << endl;
}
Run Code Online (Sandbox Code Playgroud)

为什么我会出现分段错误?这是控制台输出(用g ++ -o test test.cpp -g编译)

./test
Test String 
zsh: segmentation fault  ./test
Run Code Online (Sandbox Code Playgroud)

派生的v.end()类的这个指针并没有指向正确的位置......但为什么呢?

Yak*_*ont 13

end()不是指向最后一个元素的迭代器.它指向一个过去的最后一个元素.解除引用end()是非法的.

back()如果您想要最后一个元素,请使用.

  • 根据你正在做的事情,`rbegin()`也可能是合适的. (2认同)