What are the drawbacks of forward declaration?

前端 未结 5 1354
暗喜
暗喜 2021-01-14 13:09

I am wondering if there is any drawback for using forward declarations in all places when possible. This is if my header contains only declarations.

As far as I unde

5条回答
  •  离开以前
    2021-01-14 13:49

    I'll speak in practical terms. Pros:

    1. Avoids circular compiler dependencies. The way you wrote the code above would not even compile otherwise unless you put A and B in the same header.

    2. It avoids compile-time dependencies. You're allowed to change a.h without recompiling units that include b.h. For the same reason, it speeds up builds in general. To find out more on this subject, I recommend looking up the Pimpl idiom.

    Cons:

    1. Applied heavily in this way you have above, your general source files will probably need to include more headers (we cannot instantiate or work with A simply by including B.h). To me, that's a worthwhile exchange for faster builds.

    2. This is probably the biggest con which is that it can come with some runtime overhead depending on what you are doing. In the example you gave, B cannot directly store A as a value. It involves a level of indirection, which may also imply an extra heap allocation/deallocation if B is the memory manager of A (the same would be true of a pimpl). Whether this overhead is trivial or not is where you have to draw the line, and it's worth remembering that maintainability and developer productivity is definitely more important than a micro-optimization which won't even be noticeable to the user. I wouldn't use this as a reason to rule out this practice unless it is definitely proving to be a bottleneck or you know well in advance that the cost of a heap allocation/deallocation or pointer indirection is going to be a non-trivial overhead.

提交回复
热议问题