我正在用 C++ 做一个关于 OOP 的项目,但遇到了一些错误(分段错误)。
sObjects
是一个静态向量,包含指向Base
类中创建的每个对象的指针。
我还通过取消注释这些行来检查地址:// cout<<(*it)<<endl;
// cout<<this<<endl;
。它们是相同的。
那么为什么我会收到垃圾值/分段错误?我必须做某种铸造吗?
这是我的代码:
//main.cpp
#include <iostream>
#include "Base.h"
using namespace std;
int main()
{
Base::UnitTest();
vector<Base *>::iterator it;
for (it = Base::sObjects.begin(); it < Base::sObjects.end(); ++it)
{
// cout<<(*it)<<endl;
cout<<(*(*it))<<endl;
}
return 0;
}
//Base.h
#ifndef BASE_H
#define BASE_H
#include <iostream>
#include <vector>
using namespace std;
struct Node{
int val;
};
class Base
{
private:
Node node_;
public:
Base(int a=0);
~Base();
static vector<Base*> sObjects;
friend ostream &operator<<(ostream &os, const Base &myObj);
static void UnitTest();
};
#endif
//Base.cpp
#include "Base.h"
vector<Base*> Base::sObjects;
Base::Base(int a)
{
this->node_.val=a;
sObjects.push_back(this);
// cout<<this<<endl;
}
Base::~Base()
{
}
ostream &operator<<(ostream &os, const Base &myObj)
{
os<<myObj.node_.val;
return os;
}
void Base::UnitTest()
{
Base obj(23);
}
在中创建的对象Base::UnitTest()
超出范围,但是sObjects.push_back(this);
在它不再存在后,您将其指向它的指针保留在您的向量中。这是一个悬空指针的实例。这是未定义的行为。任何事情都可能发生,包括它在某些时候似乎有效。幸运的是,您发现它不适用于您的情况。如果它即使坏了也能工作,情况会更糟。
相关:什么是悬空指针?
在同样的链接中,这是使用生命周期已结束的指针的情况。使用指向生命周期已结束的对象的指针(例如,堆栈分配的对象或删除的对象)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句