Reputation: 59
While searching the doc on cppreference.com, I've seen that some features are defined multiple times in different headers...
For example: std::move
(in <algorithm>
and <utility>
), std::size_t
, etc (see below).
The page about std::size_t
starts with this precision:
Defined in header <cstddef> Defined in header <cstdio> Defined in header <cstdlib> Defined in header <cstring> Defined in header <ctime> Defined in header <cuchar> (since C++17) Defined in header <cwchar>
Why is this the case? And which header should one choose rather than any other?
Upvotes: 2
Views: 104
Reputation: 80
You can simply add #include<bits/stdc++.h> that will import all the necessary libraries for you, But sometimes it is not advisable to include all the libraries then you have to include specific libraries.
Upvotes: -2
Reputation: 170064
Every standard library header needs to be self contained. If we want to use it, we are not to be forced into including anything else. Since all of the headers in the list you cite end up using size_t
in some capacity, including them must also make size_t
available. So it's standard mandated behavior.
Mind you, that the wording in cppreference is a bit misleading. It's not that every header always defines the type alias. It's more than likely that the actual definition is in some internal implementation specific header, that all of those public headers include it themselves.
So the behavior in essence, is that there is only ever one "true" definition of size_t
. And you can get it by including any of the above headers.
As for which one to choose? You can examine the synopsis of each header. If all you need is size_t
then cstddef
is the most minimal header that includes it.
Upvotes: 2
Reputation: 4207
Why is this the case?
2 reasons I can think of.
The function declarations and anything else in the headers use size_t
and therefore need to declare it (same with any other thing).
(Maybe) Convenience. size_t
for example is used in a lot of cases so it's simpler to have size_t
just from including, for example <iostream>
rather than having to include <cstddef>
too.
And which header should one choose rather than any other?
It appears someone else had the same question. Though I'd say take advantage of size_t
being in multiple headers. If you only need <iostream>
for a program, no need to include <cstddef>
as well just for the sake of it.
Upvotes: 1