【问题标题】:Using constant pointers to avoid includes使用常量指针避免包含
【发布时间】: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


【解决方案1】:

这是最大限度地减少标题包含的完全合法和标准的方法。实际上,一种可行的方法是始终通过指向结构的不透明指针访问所有私有成员,以便公共标头只是

namespace detail {
    struct xxFoo_impl;
}

class Foo {
    detail::xxFoo_impl* xx;
    public:
    // ... stuff ...
};

那么,在Foo.cpp中,xxFoo_impl定义了所有的成员变量,构造函数在堆上分配xx,所有对变量的访问都是通过xx指针。这样,对类的私有成员的更改不会影响代码的任何客户端:标头未更改,它们不需要重新编译。

因此,不仅可以使用指针来减少标题中的内容,甚至还建议这样做。 ;-)

但如果Foo 的用户都希望访问Bar 成员,那么没有意义,因为无论如何他们都会包括bar.h

【讨论】:

    猜你喜欢
    • 2013-03-24
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 2017-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多