使用常量指针避免包含
问题描述:
我的目标是通过最小化包含来减少编译时间,同时保持对类范围内的内存分配的控制。使用常量指针避免包含
实例化方法
foo.h中
#include "Bar.h" //unneccessary if only number is used in a given source file
struct Foo
{
Bar bar;
int number;
};
常数指针方法
foo.h中
struct Bar; //no include, to use Bar Bar.h must also be included
struct Foo
{
Bar *const bar;
int number;
Foo();
Foo(const Foo&) = delete;
~Foo();
};
Foo.cpp中
#include "Bar.h"
Foo::Foo()
: bar(new Bar())
{
}
Foo::~Foo()
{
delete bar;
}
是否有使用常量指针这样的,而不是实例变量任何其他注意事项?或者可能的替代方法?
答
这是一个完全合法和标准的方法来最小化头包括。事实上,一个可行的办法是,总是通过一个不透明的指针访问所有的私有成员的结构,使公众头球攻门仅仅高出
namespace detail {
struct xxFoo_impl;
}
class Foo {
detail::xxFoo_impl* xx;
public:
// ... stuff ...
};
然后,在Foo.cpp中,xxFoo_impl
与所有成员定义变量,构造函数在堆上分配xx
,并且所有对变量的访问都通过xx
指针。这样,对类的私有成员的更改不会影响代码的任何客户端:头不变,不需要重新编译。
所以,不仅是使用指针来减少标头中的东西,甚至还建议使用。 ;-)
但是,如果Foo
的用户都预计会访问Bar
成员,那么没有意义,因为他们都将包括bar.h
。
当模块出现时,这种过度的聪明会让你陷入困境。只需包括你需要的东西。 –
其他的注意事项你的意思是超出你完全破解的拷贝构造函数和手动使用'new'的东西吗? –
准确的说:)复制构造不是必需的用例我有,所以我很高兴删除它们。已经更新了这个问题。你可以扩展'手动使用新',以及这是一个问题与任何其他使用新的问题相比?谢谢! –