面试真题

C++ · 中等 · 阿里巴巴

C++ Pimpl了解吗?有什么好处?

中等 C++ 🎤 阿里巴巴
参考答案
结论:Pimpl(Pointer to Implementation)是隐藏类实现细节的惯用法,在头文件仅前置声明实现结构体并用智能指针持有。要点:类A中定义struct Impl; std::unique_ptr<Impl> pImpl; 具体成员放在cpp的Impl中;好处:降低编译依赖,修改私有成员不需重编调用方;加快编译速度;隐藏专有实现,减少头文件耦合;支持库二进制兼容。注意析构函数必须在cpp中定义以使Impl完整。示例:class Widget { struct Impl; std::unique_ptr<Impl> p; public: Widget(); ~Widget(); void api(); }; 实现全在cpp。
题目整理自公开面经,答案由校招宝自研生成,仅供参考