Explicit direct #include vs. Non-contractual transitive #include

后端 未结 6 2159
傲寒
傲寒 2021-02-12 12:47

Say we have this header file:

MyClass.hpp

#pragma once
#include 

class MyClass
{
public:
    MyClass(double);

    /* ... */

private:
            


        
6条回答
  •  被撕碎了的回忆
    2021-02-12 13:16

    to prevent a dependency on the internal workings of MyClass. Or should I?

    Yes, you should and for pretty much for that reason. Unless you want to specify that MyClass.hpp is guaranteed to include , you cannot rely on one including the other. And there is no good reason to be forced to provide such guarantee. If there is no such guarantee, then you rely on an implementation detail of MyClass.hpp that may change in future, which will break your code.

    I obviously realise that MyClass needs vector to work.

    Does it? Couldn't it use for example boost::container::small_vector instead?

    In this example MyClass needs std::vector

    But what about the needs of MyClass in future? Programs evolve, and what a class needs today is not always the same that the class needs tomorrow.

    But would it not be good to be able to decide which headers get exposed when importing

    Preventing transitive inclusion is not possible.

    Modules introduced in C++20 are a feature that may be used instead of pp-inclusion and are intended to help solve this.

    Right now, you can avoid including any implementation detail dependencies by using the PIMPL pattern ("Pointer to implementation"). But PIMPL introduces a layer of indirection and more significantly, requires dynamic allocation which has performance implications. Depending on context, these implications may be negligible or significant.

提交回复
热议问题