看看这个片段:
#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;
}
为什么会出现分段错误?这是控制台输出(使用 g++ -o test test.cpp -g 编译)
./test
Test String
zsh: segmentation fault ./test
派生类 v.end() 的 this 指针没有指向正确的位置……但是为什么呢?