【发布时间】:2016-05-15 18:47:17
【问题描述】:
我的目标是通过最小化包含来减少编译时间,同时在类范围内保持对内存分配的控制。
实例化方法
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;
}
在使用像这样的常量指针而不是实例变量时还有其他注意事项吗?或者也许是其他方法?
【问题讨论】:
-
当模块出现时,这种过度的聪明会给你带来麻烦。只需包含您需要的内容。
-
其他警告是指超出完全损坏的复制构造函数和手动使用
new之外的东西吗? -
正是这样 :) 我的用例不需要复制构造,所以我很高兴删除它们。已更新问题。您能否详细介绍“手动使用 new”,以及与任何其他使用 new 相比,这是一个问题吗?谢谢!
-
使用 unique_ptr 并且不必使用 delete。
-
你也在用编译时间换运行时间。并不总是最有效的。
标签: c++ pointers include constants member