默认构造函数/析构函数的单独定义和声明有什么意义(例如,更快的编译速度)?我遇到了这样的设计,但我不明白为什么有人不仅仅将其保存在.hpp文件中。
// A.hpp
class A
{
public:
A();
~A();
};
Run Code Online (Sandbox Code Playgroud)
// A.cpp
#include "A.hpp"
A::A() = default;
A::~A() = default;
Run Code Online (Sandbox Code Playgroud)
考虑使用智能指针实现的PIMPL习惯用法:
// X.h:
class X {
class Impl;
std::unique_ptr<Impl> pimpl_;
public:
~X() = default;
...
};
Run Code Online (Sandbox Code Playgroud)
在源文件中包含这样的头文件将导致编译错误,因为X::Impl那里的文件类型不完整,因此无法删除。
一种解决方案是将析构函数定义移至源中:
// X.h:
class X {
class Impl;
std::unique_ptr<Impl> pimpl_;
public:
~X();
...
};
Run Code Online (Sandbox Code Playgroud)
加:
// X.cpp:
class X::Impl { ... };
X::~X() = default; // X::Impl is complete here
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55 次 |
| 最近记录: |