2025-09-05 避免C++异常处理中的对象切片:引用捕获的实战技巧 避免C++异常处理中的对象切片:引用捕获的实战技巧 一、对象切片的致命陷阱当我们在catch块中按值捕获异常对象时,编译器会悄悄执行对象切片(Object Slicing)。这个隐蔽的行为可能摧毁整个异常处理的价值:cpp class BaseException { public: virtual const char* what() const { return "Base Exception"; } };class DerivedException : public BaseException { public: const char* what() const override { return "Derived Exception with additional data"; } };try { throw DerivedException(); } catch (BaseException e) { // 切片发生! cout << e.what(); // 输出"Base Exception" }此时DerivedEx... 2025年09月05日 5 阅读 0 评论