ana*_*lyg 2 c++ forward-declaration c++-standard-library c++11
我经常使用前瞻性声明; 它们有助于避免许多问题#include,缩短编译时间.但是如果我想在标准库中转发声明一个类呢?
// Prototype of my function - i don't want to include <vector> to declare it!
int DoStuff(const std::vector<int>& thingies);
Run Code Online (Sandbox Code Playgroud)
我听说有人禁止/无法向前宣布std::vector.现在这个无关问题的答案建议用这种方式重写我的代码:
stuff.h
class VectorOfNumbers; // this class acts like std::vector<int>
int DoStuff(const VectorOfNumbers& thingies);
Run Code Online (Sandbox Code Playgroud)
stuff.cpp
// Implementation, in some other file
#include <vector>
class VectorOfNumbers: public std::vector<int>
{
// Define the constructors - annoying in C++03, easy in C++11
};
int DoStuff(const VectorOfNumbers& thingies)
{
...
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我在整个项目中使用VectorOfNumbers而不是std::vector<int>在所有上下文中,一切都会很好,我不再需要#include <vector>在我的头文件中了!
这种技术有哪些主要缺点?能够向前宣布的收益能否vector胜过他们?
如果你删除a VectorOfNumbers作为a std::vector<int>(并且因为你使用了公共继承,这种转换是隐式的)你已经进入了未定义行为的领域.这可能比人们怀疑的更容易发生.
我从未亲自注意到只vector需要包含所需的重要编译速度,但是如果你真的想要隔离include,请使用不了解底层容器类型的客户端API接口(vector)并将vectorinclude包含到单个源中文件.