java编程惯用法_减少编译时依赖的意义和一些惯用法

http://herbsutter.com/2013/08/19/gotw-7a-solution-minimizing-compile-time-dependencies-part-1/

GotW #7a Solution: Minimizing Compile-Time Dependencies,Part 1

2013-08-19 by Herb Sutter

减少编译时依赖的意义和一些惯用法

1. For a function or a class,what is the difference between a forward declaration and a definition?

A forward declaration of a (possibly templated) function or class simply introduces a name。

A class definition has a body and lets you know the class’s size and know the names and types of its members

前置声明(forward declaration):只是引入了一个名字符号;

包含引用类的定义头文件:引入一个类型的完整定义(definition),如:需要了解有哪些构造函数,成员函数,类的大小等。

class widget; // "widget" names a class

widget* p; // ok: allocates sizeof(*) space typed as widget*

widget w; // error: wait,what? how big is that? does it have a

// default constructor?

===================================

// x.h: original header

//

#include

#include

#include

// None of A,B,C,D or E are templates.

// Only A and C have virtual functions.

#include "a.h" // class A

#include "b.h" // class B

#include "c.h" // class C

#include "d.h" // class D

#include "e.h" // class E

class X : public A,private B {

public:

X( const C& );

B f( int,char* );

C f( int,C );

C& g( B );

E h( E );

virtual std::ostream& print( std::ostream& ) const;

private:

std::list clist;

D d_;

};

==========================

std::ostream& operator<

return x.print(os);

}

1. Remove iostream.

Guideline: Never #include unnecessary header files.

永远不要#include多余的头文件。

2. Replace ostream with iosfwd.

Parameter and return types only need to be forward-declared,so instead of the full definition of ostream we really only need its forward declaration.

Guideline: Prefer to #include when a forward declaration of a stream will suffice.

优先使用 前置声明 代替 #include定义头文件。如,类型如果只用于函数参数,返回值类型,只需前置声明。

std::ostream& operator<

return x.print(os);

}

This function mentions an ostream& as both a parameter and a return type,which most people know doesn’t require a definition. And it passes its ostream& parameter in turn as a parameter to another function,which many people don’t know doesn’t require a definition either—it’s the same as if it were a pointer,ostream*,discussed above. As long as that’s all we’re doing with the ostream&,there’s no need for a full ostream definition—we’re not really using an ostream itself at all,such as by calling functions on it,we’re only using a reference to type for which we only need to know the name. Of course,we would need the full definition if we tried to call any member functions,for example,but we’re not doing anything like that here.

当仅需一个类型的引用时,只需前置声明,因为只是需要知道类型的名字。但如果通过类型引用访问其成员,则需要完整定义。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值