Should I include <tuple>? - c++

I am a newbie in c++, and I suspect, that, of course the question relates not only to tuple.
So, I've watched a tutorial with roughly this code:
#include <tuple>
std::tuple<...> t(...)
Why #include <tuple>? Especially, given the fact that we explicitly write std::tuple. The code compiles without that #include line just well...

Because <tuple> is a header file which contains the tuple class inside the namespace std. Just because you're explicitliy saying std:: doesn't mean the compiler will just be able to find it if it's not included.
The reason it worked for you in this case is probably because another header you have included already includes <tuple> and thus your code includes <tuple> indirectly or because the compiler you're building with includes it automatically. This is not guaranteed by the standard and should not be relied upon. Always include the headers you'll need to make your code portable.

You always should include the specific headers for any types that you use in your code.
The code compiles without that #include line just well...
That your code compiles without is just by chance, because it might have been included by another standard header you use in your program, and not guaranteed by the standard, and thus not portable.
Especially, given the fact that we explicitly write std::tuple.
The explicit use of the std:: namespace doesn't have any significance about that rule.
You should also always be explicit about using classes or types from the std namespace to prevent getting into ambiguity troubles.
Related stuff:
Why is “using namespace std;” considered bad practice?
Why should I not #include ?
How do I include the string header?

In C++ you need to include the header for everything you use. The std:: is about the namespace, it's completely different.
Apparently your compiler is smart enough to deal with it, but most of the compilers won't.

Some standard headers shall include other standard headers according to the C++ Standard. For example the header <algorithm> must include the header <initializer_list>.
However implementations are allowed to include standard headers in other standard headers at their discretion.
You should not rely on this because your program compiled with one compiler will not compile using another compiler.
Even if one standard header is included in another standard header according to the requirements of the C++ Standard nevertheless it is a good practice to include such a header explicitly because the user of the program (some other programmer) should bother about dependencies of the headers and will be free to include or exclude other headers.

Related

How can I determine what header calls another header in c++?

I am reading from here : Can std::string be used without #include <string>?, <iostream> is calling <string>. But I do not see any includes of <string> in Standard library header <iostream> from c++ standard: https://en.cppreference.com/w/cpp/header/iostream. In <iostream> is only included <ios>, <streambuf>, <istream> and <ostream> according to that documentation. So this code works (file foo.cpp):
#include <iostream>
int main(){
std::cout << "enter srting\n";
std::string out; //std::string should not be included according to standard documentation
std::cin >> out;
std::cout << "test, " << out;
}
But I have to try to see dependecies generated from gcc:
cc -H foo.cpp |& vim -
and the output is (I have regex out files with string in it):
. /usr/include/c++/8/iostream
..... /usr/include/c++/8/bits/stringfwd.h
...... /usr/include/c++/8/string
....... /usr/include/c++/8/bits/basic_string.h
........ /usr/include/c++/8/ext/string_conversions.h
....... /usr/include/c++/8/bits/basic_string.tcc
So I can see that in the end, many "string" headers are indeed included
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
Some of them are deeper on the #include stack (term from gcc manual), which brings me to question,
what calls what? And what is the "true" header, that define std::string of them? (is it /usr/include/c++/8/bits/basic_string.h?...)
from this question Why does omission of "#include <string>" only sometimes cause compilation failures?, they mentioned:
Some compilers on some platforms may on some time of the month compile even though you failed to include the header
But from the upper output of the "string headers", there is multiple of them , so how's possible for a compiler to compile only sometimes? Which of these headers are really important for successful compilation?
How to orient in cpp headers, which are meaningful for compiler, and could be tracked their "#include stack" (i.e. other meaningful headers)?
EDIT:
If it depends on my specific implementation of my stdlib++, then I want to know how can I determine from source whether that inclusion is made before I try to compile. Not by "If it compiles, then it works".
In general you cannot know what headers are transitively included by the headers you include, and any standard header is allowed to, but not required to, include any other header. And you shouldn't rely on transitive includes ever. You should include the headers you need for the things that you use and then you'll be good.
You should always check the documentation for any symbol you use and include any headers it is specified to require.
The C++ standard only specifies which symbols must be made available when a standard header is included. It does not place any limits on what other symbols are made available. In your example, the standard specifies the <iostream> must include <ios>, <streambuf>, <istream>, and <ostream>, but <iostream> may include any other headers its authors want. It may also forward-declare any symbols it may need.
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
You should trust that the symbols specified as being available when you include <string> will be. That is all. You may not assume that those symbols will not be visible when including any other header.
what calls what? And what is the "true" header, that define std::string of them? (is it /usr/include/c++/8/bits/basic_string.h?...)
This is an implementation detail that can only be answered by inspecting the implementation's headers. Libstdc++ (the standard library implementation used by GCC) has the declaration of the std::string class in bit/stringfwd.h and its definition in bits/basic_string.h and bits/basic_string.tcc (for the current version, at least), but that is not required at all. If the libstdc++ maintainers decided they wanted to refactor and reorganize things, they would be free to do so. The only requirement that is guaranteed by the C++ language is that std::string must be available when <string> is included.
But from the upper output of the "string headers", there is multiple of them, so how's possible for a compiler to compile only sometimes?
Different standard library implementations or different versions of the same implementation could transitively include different headers. Different compiler flags (i.e. a debug flag or different standard compliance mode) could transitively include different headers.
Which of these headers are really important for successful compilation?
How to orient in cpp headers, which are meaningful for compiler, and could be tracked their "#include stack" (i.e. other meaningful headers)?
All of them are meaningful. The standard library's authors wouldn't include a header if they didn't need it for something. Just because you aren't using any symbols declared/defined in that header directly doesn't mean none are being used.
EDIT: If it depends on my specific implementation of my stdlib++, then I want to know how can I determine from source whether that inclusion is made before I try to compile. Not by "If it compiles, then it works".
The only way to know is to look at your standard library implementation's headers. There is nothing magical about them; they're just C++ code. If you want to know if <iostream> includes a declaration or definition of std::string, open your implementation's copy of <iostream> and look for a declaration or definition of std::string. Repeat this process for any headers that <iostream> includes.
<iostream> is calling <string>
Do you mean that it includes <string>? Calling is something that is done to functions.
But I do not see any includes of <string> in Standard library header <iostream> from c++ standard: https://en.cppreference.com/w/cpp/header/iostream.
What you're reading is documentation of <iostream>. Indeed, <iostream> is not documented to include <string>.
So this code works (file foo.cpp):
It may work with some standard library implementation. It may not work using other implementations.
(so should I trust that documentation, when the did not mentioned <string> header in "Includes" list of <iostream>?).
cppreference is fairly high quality. Unless it contradicts the standard, it is fairly safe to assume that it is correct. Indeed in this regard it is correct: <iostream> is not guaranteed to include <string>.
what calls what?
Some headers include some other headers. There is no need to know more accurately than that because you should not rely on transitive inclusions (except those that are documented).
And what is the "true" header, that define std::string of them?
As per documentation, std::string is defined in header named string (commonly stylised as <string> which matches the conventional inclusion syntax).
so how's possible for a compiler to compile only sometimes?
It could ask the current time from the operating system and use a branch to do one thing or another depending on that time. Compilers don't typically do that, but the point is that they could.
More realistically, you may at some point need to compile your program using another (version) of the compiler (or standard library implementation). Different implementations behave different from one another.
Which of these headers are really important for successful compilation?
The ones that are documented to define and declare the names whose definitions and declarations your program relies on. If you use std::string, then you must include the header that defines std::string which is <string>.

Is it undefined behavior to have your own header with the same name as a standard header?

I have realized that for years I have my own header named algorithm.h.
I always include it with:
#include "algorithm.h"
as opposed to the inclusion of the standard header:
#include <algorithm>
I have never had any problems (not even warnings in gcc) with ambiguity but I wonder if it was just luck. I like the name of my header and I do not want to rename it just out of fear.
In case it is not undefined behavior, is it considered to be bad style?
No, it's not undefined behaviour. The Standard doesn't say anything about any headers other than the ones that are part of the standard library. In fact, it even specifies (C++11, section 16.2.3 [cpp.include]) that if you were to do something like
#include "algorithm"
and the header isn't found, then it does the same thing as
#include <algorithm>
Whether having a header called algorithm.h is bad style is debatable. I would avoid it because it might confuse programmers with less experience in C++. However, something like utils/algorithm.h would be perfectly fine, if you ask me.
This is definitely not good style and you did get reasonably lucky.
What is happening is when you surround the file with quotes
#include "algorithm.h"
the compiler looks for the header in user-defined paths first.
When you surround the file with brackets,
#include <algorithm>
the compiler checks system folders for the header file first.
Therefore both header files get included. You do however need to watch out for overriding of variables defined in the separate header files.
Hope this helps!

Header file for pair stl

I am used to writing codes using stl pair without including any specific header file for using pair. But a friend today told me that I should use utility header whenever I use pair else I will have problem on some compilers. Please tell if this is true. And what is the use of utility header if I can write codes without using it.
You should almost always include header file for every class which you use in your program, otherwise you depend on the fact that some headers internally use a class of your interest, but this can change on another compiler or version. You need to read reference of a class (for example on cppreference.com - http://en.cppreference.com/w/cpp/utility/pair ) and check which header file you need to include - in case of std::pair you should add #include <utility> . You cannot depend on the fact, that, for example, iostream already includes iomanip and your code compiles when you use manipulators like setw etc. You cannot - you always should refer to language specs and include required headers.
The point is that you may have had indirectly included the <utility> header through the inclusion of some other header. Usually it is the case that headers are included by other headers in a C++ implementation without that inclusion being mandated by the standard. So, by including <utility>, you make sure your code is portable across standard compliant implementations (at least with respect to this particular issue).
The standard specifies that std::pair is in <utility>, so you should include this whenever you use an std::pair.
You always need to include the headers defining the components you use. Some standard libraries will be implemented to include other declarations they use internally butyou can't rely on this, at all. I consider it an error that standard libraries make declarations available they are not required to make available.
The class template std::pair is made available by <utility>.

Strange C++ behaviour involving iostream and wstring

I have two files, my_program.cpp and its header my_program.h.
my_program.cpp contains only this:
#include "my_program.h"
using namespace std;
my_program.h contains a pointer to a function which returns a wstring, as follows:
using namespace std;
typedef wstring (*my_function)(wstring, int, int, int, int);
The program doesn't compile in this state (stops at typedef... saying that ISO C++ forbids declaration of 'wstring' with no type) but if I add #include <iostream> before #include "my_program.h" in the .cpp file, the program miraculously compiles.
Why does this happen? I just hope I didn't make a foolish mistake and I'm now going to be laughed at.
You really should include <string>.
From the sound of things, your compiler's <iostream> happens to include <string>, so it works, but on a different compiler it may not. C++ allows a standard header to include other standard headers, but doesn't require it. In some cases, you get only a declaration of the class, so some things work, and others don't.
At least in my experience, this is also an issue that's likely to change from one version of a compiler to the next, so even if you don't intend to port to anything else, your code may quit working just due to a seemingly trivial upgrade unless you include the right header.
Before you add #include <iostream>, the compiler has no idea what wstring is -- hence the error
After you include the iostream header, (which defines std::wstring -- possibly via other headers it includes), the compiler knows what wstring refers to and can properly parse the typedef.
One thing to keep in mind is that the compiler only cares about what's called the compilation unit (.cpp files), not the headers; the headers come into play when a compilation unit includes them (think of verbatim copy-paste). Therefore you can include iostream (or as others pointed out <string>) anywhere before the typedef, to make it work -- from this perspective, including it before the header counts the same as including it at the first line of the header.
It is generally a good idea, however, to make headers as self consistent as possible (so in your case include the relevant headers in your header, instead of the .cpp), so the includers do not need to remember what other headers to include as well to make it work as intended.

Is there any guaranteed dependency of C++ system headers?

For example, in <algorithm>, the function equal_range returns a pair, so can I assume that if I #include <algorithm>, <utility> is #included?
There is never a guaranteed inclusion of header files that other headers depend on. Fortunately, it's common practice (though not certain 100% of the time) that headers are guarded against multiple inclusion -- meaning you can #include them as many times as you wish without causing harm.
You should always include what you need, you cannot rely on all implementations including the same set of headers in another header.
In your example, if a function returns a pair you can be reasonably sure that the pair class is declared, but nothing requires the implementation to include the rest of <utility>.
In fact, it is impossible to implement the standard library using exactly the headers shown in the standard, because there are some circular references. Implementations must split them in smaller parts, and include those sub-headers in the required <> headers.
The GCC team, for example, is working to minimize the amount of inclusions to speed up compile time.
OK, late answer, but I'll add this anyway.
It's about the <iostream> header. In C++98 and C++03 the standard did not guarantee that it would include <istream> and <ostream>, which meant that you were not guaranteed to have available e.g. std::endl. And at least one compiler insisted on being formal about it (in spite of all the non-normative examples in the standard showing the intention)!
Well, I can't remember who pointed it out first, but it was discussed up, down and sideways in [comp.lang.c++]. Several times. And finally James Kanze, bless his soul (well he's not dead yet, in fact he's here on SO), put it to the committee, and it was fixed for C++0x.
So, there's now one header dependency that you can depend on.
Hallelujah!
But in the other direction, C++0x increases the confusion about which headers can put which names in the global namespace and the std namespace. Now any standard library header corresponding to a C library header can freely pollute the global namespace, and be conforming. And so now there's no point in including, say, <cstdio>, but instead now the wise thing to do is to include <stdio.h> and accept a guaranteed global namespace pollution.
Cheers & hth.,
Yeah, you should not assume anything about inclusion of headers. I have been playing around with inclusion of headers for a while, and you know i observed that when it comes to header files like vector and string, you are 'almost' sure that you are including them from somewhere.
Yes but this things are good only when you are just playing around. I would suggest you to always include the headers.
There is no guarantee, but since <algorithm> uses pair internally it is common sense that it should include it. There are ways to make sure that a header file is included only once:
#pragma once http://en.wikipedia.org/wiki/Pragma_once
#ifndef MY_H
#define MY_H
//header code
#endif /* MY_H */
And usually a good library will include all the needed files to compile, and those will be using this kind of mechanism to make sure that they are included only once.
There are sometimes exceptions to this rule especially in private (personal, not standard) libraries where the included header files are placed in the order needed for them to compile. And in that case if you have three includes, probably the second include uses the code from the first and the third from the first and second.
Best approach is to include all that you need to have direct access to the data structures you use.