gpt4 book ai didi

c++ - 我可以在调用纯虚函数时禁用异常吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:24:43 24 4
gpt4 key购买 nike

我有一些看起来像这样的代码:

class Writable {
public:
virtual void putc(const char ch) = 0;
protected:
virtual ~Writable() {};
};

class Readable {
public:
virtual char getc() = 0;
protected:
virtual ~Readable() {};
};

注意两个虚函数。使用 arm-none-eabi-gcc 编译此代码(连同我的其他代码),并与 -fno-exceptions 链接产生此输出:

arm-none-eabi-size  --format=berkeley bareCortexM.elf
text data bss dec hex filename
108948 2304 2372 113624 1bbd8 bareCortexM.elf

用方法 stub 代替纯虚函数再次运行它会产生:

arm-none-eabi-size  --format=berkeley bareCortexM.elf
text data bss dec hex filename
47340 2296 304 49940 c314 bareCortexM.elf

这种巨大的差异似乎是由于异常造成的。有什么办法可以防止这种情况发生吗?

最佳答案

这篇博文对此进行了描述:Smaller binary size with C++ on baremetal (g++)

Provide a __cxa_pure_virtual() implementation

If you use pure virtual functions anywhere but have disabled exceptions, you may notice your code suddenly inflate again.

This happened to me, and it took a while to track down, whoops!
Inspecting assembly listing of the final binary (from objdump -h -C -S), it looked like exceptions were coming back!

One thing I tried was linking with -nostdlib, completely pulling libstdc++ out of the picture. I provided dummy implementations of malloc, realloc, free, and a few other stdlib functions I used, but then avr32-g++ complained about something I hadn’t seen before: I was missing __cxa_pure_virtual().

Aha,” I thought, “this has to be it!” In the source of that particular function, found in libstdc++, is a call to std::terminate(), seen here. That call threw a lovely party all over my poor AVR32′s flash memory, trampling on -fno-exceptions on their way in.

Anyway, __cxa_pure_virtual() is what actually gets called when you call a pure virtual function. Like new and delete, this is probably something you want to override anyway so your own debug/trace code can give you useful feedback. The implementation is straightforward, just be sure to make it extern "C" so the name doesn’t get mangled:

extern "C" void __cxa_pure_virtual() { while(1); }

关于c++ - 我可以在调用纯虚函数时禁用异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14689639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com