调用静态对象的重写函数时出现异常
GCC: exception when calling an overridden function of a static object
我使用GCC 3.4.3。该设备是基于ARM9/ARM11的POS终端PAX S80。下一个测试代码可以正常编译,但是在运行时调用被覆盖的函数时,我得到一个异常。
class TBase {
public:
int a;
virtual void Foo() {a = 1;}
void Exec() {Foo();}
};
class TDerived : public TBase {
public:
virtual void Foo() {a = 2;}
};
TBase *Base; //pointer to object in heap
TBase Base2; //static object
TDerived *Derived; //pointer to object in heap
TDerived Derived2; //static object
int main() {
Base = new TBase;
Base->Exec(); //this passes okay
Base2.Exec(); //this passes okay
Derived = new TDerived;
Derived->Exec(); //this passes okay
Derived2.Exec(); //here I get an exception and the app crashes
return 0;
}
这意味着我不能使用静态对象(Derived2)。是的,我可以在代码中创建对象(派生),但它使代码复杂化,因为我需要用"new"操作符实例化对象。
有什么技巧可以避免这个问题吗?
顺便说一下,我在ARM926的Keil编译器上没有这个问题。不幸的是,我不能为这个设备选择编译器,只能选择GCC 3.4.3。谢谢你的建议!
原因是没有初始化静态对象。所以,我决定手工完成。
首先,我将下面几行添加到链接器脚本中(源代码):__ctors_start__ = .;
KEEP(SORT(*)(.ctors))
__ctors_end__ = .;
其次,我调用一个函数,该函数调用静态对象(源)的所有构造函数:
void do_ctor_calls() {
typedef void (*call_ctor_t)(void);
extern call_ctor_t __ctors_start__[];
extern call_ctor_t __ctors_end__[];
call_ctor_t * ctor_call = __ctors_start__;
while ((ctor_call < __ctors_end__)&&((unsigned int)*ctor_call!=0xFFFFFFFF)&&((unsigned int)*ctor_call!=0x00000000)) {
(*ctor_call)();
ctor_call++;
}
}
int main() {
do_ctor_calls();
/* My code here */
return 0;
}
最终,被重写的函数可以正常工作,静态对象可以正常操作。谢谢大家! 相关文章:
- 从构造函数抛出异常时如何克服内存泄漏
- 创建具有 new in 函数和"this is nullptr"异常的对象
- 函数如何通知用户它基于函数原型抛出异常?
- C++/CLI System.AccessViolation在托管类中调用非托管函数时出现异常
- 如何编写带有异常的构造函数
- 有没有办法捕获 STL 函数未被赋予正确参数的异常?
- 在缺少函数重载时抛出异常,并带有 std::variant 而不是编译时错误
- 从函数(不抛出函数)返回异常以进行消息格式化?
- 从 C++ 中异常的构造函数引发异常
- 赋予全局变量而不是局部变量优先级的函数 - (异常行为)
- 是否允许分配器构造和销毁成员函数从内部逻辑引发异常?
- 调用参数不是原子参数的函数是此代码引发异常的原因吗?
- (此函数用于计算 SMA).在 FA.exe 中0x00509159引发异常: 0xC0000005:访问冲突读取位置0
- 我正在尝试创建一个使用 c++ 中的参数包构造函数的异常类
- C++中函数出现Bad_alloc异常
- 为什么 c++ 使用 throw() 关键字来指示函数不会引发任何异常
- 在析构函数内部处理异常(但不抛出)
- 在OpenCV_core310.dll中使用findContours函数时,OpenCV引发未处理的异常
- 为sLinkedList编写插入函数时引发异常
- c++运算符=工作异常(函数内部输出正常,但返回后错误)