创建由其他类组成的类时,是否值得通过使用指针而不是值来减少依赖关系(从而减少编译时间)?应该使用指针来减少头依赖关系吗?
例如,以下使用值。
// ThingId.hpp
class ThingId
{
// ...
};
// Thing.hpp
#include "ThingId.hpp"
class Thing
{
public:
Thing(const ThingId& thingId);
private:
ThingId thingId_;
};
// Thing.cpp
#include "Thing.hpp"
Thing::Thing(const ThingId& thingId) :
thingId_(thingId) {}
但是,下面的修改版本使用指针。
// ThingId.hpp
class ThingId
{
// ...
};
// Thing.hpp
class ThingId;
class Thing
{
public:
Thing(const ThingId& thingId);
private:
ThingId* thingId_;
};
// Thing.cpp
#include "ThingId.hpp"
#include "Thing.hpp"
Thing::Thing(const ThingId& thingId) :
thingId_(new ThingId(thingId)) {}
我读过,推荐这样的做法,但如果你有大量的指针,就会有大量的new
调用,我想会是缓慢的一个职位。
“是否值得通过使用指针而不是值来减少依赖关系(从而编译时间)?” - 我看不到如何使用指针“减少依赖关系” - 以及它与编译时间的关系。 – Dai
没有任何关于需要“新”调用的指针。我可以编写一堆代码,并在各处指向指针,而不是一个'new'调用。 –
@Dai:你可以转发声明pointee类型,而不是'#include'这个类型完全定义的整个头文件。 –