Is it ok to put "using std::swap;" in a header? - c++

I've read that when you're swaping things in c++, you should always using std::swap;, then call swap unqualified, so it automatically picks the std:: ones for std:: and builtin types, your custom one for custom types, and the templated std:: one for everything else.
So, can I just put using std::swap; in the header that every file includes and not have to worry about it?
I understand that avoiding using in a header is common practice. However, is there a problem with it in this particular case?

The guidance for swap is to using std::swap at the most local scope possible. For certain, one in a header file that's widely included does not meet this requirement. It still pollutes the global namespace in unexpected ways (someone not expecting std::swap will be imported to the global namespace) and should be avoided just like using namespace.

The principle issue here is that you are assuming that people did not write their own swaps that happen to be better matches that do subtly or completely different things to the semantics of std::swap and related friends. For a simple example, consider
void swap(int* a, int* b);
where the contents of the pointers are swapped. Now try to swap a pair of int*. You might think that the pointers are swapped, but instead, surprise! it's the contents that are getting swapped.
Really, the guidance for swap is the same as any other- only using at the most local scope possible and no earlier and definitely not in a header.

Related

Which functions in standard C++ library should not be prefixed with std:: when used?

When I program in C++, instead of writing using namespace std;, I generally tend to use std:: prefixed components like std::cout, std::cin etc. But then I came across ADL and why you should use using std::swap;.
Many components of the standard library (within std) call swap in an unqualified manner to allow custom overloads for non-fundamental types to be called instead of this generic version: Custom overloads of swap declared in the same namespace as the type for which they are provided get selected through argument-dependent lookup over this generic version.
But in all sources about ADL, they only mention std::swap. Are there any other functions like this that I have to be beware of when using? Or for all other functions should I use fully qualified name? Or should I use unqualified name for every function in std::?
EDIT: (I wasn't clear when phrasing my initial question. Here is what I exactly intended when I was writing the question.)
Is there any other function in C++ standard libraries that is a popular candidate for ADL based customization much like std::swap, so that when I use them, I have to be cautious to use using std::foo; foo(); form instead of invoking std::foo(); directly?
Suppose you write a library that works with user supplied types. Then you might want to provide a default implementation to foo a bar. But at the same time you want to enable the user to provide their custom implementation because they might know better how to foo their custom bar.
Thats exactly what happens in the standard library with std::swap. The code that relies on ADL is inside libraries, it works with custom types, types it doesn't know until instantiated. And it can provide a default std::swap but at the same time allows the user to provide their own implementation.
In your user-code, when you know the type, then typically you want to know what function is called. Typically you do know if you want to call my::swap or std::swap and you do not need ADL to choose.
That being said, if you have to ask this quesiton then the answer is: Do not make use of ADL. (I know "If you have to ask.." is somewhat silly, but sometimes is applies just too well). Even in library code you do not always want to enable ADL, or allow it as customization. Even if you do write generic code, there might be situations where you need your way to foo a bar without allowing the user to customize it. It really depends.
Short answer: If you want to call std::swap then call std::swap. If you want to call my::swap then call my::swap. If you want to make use of ADL you will know what to do.
PS: There are more examples of ADL that you know but might not be aware of. You almost never use the std:: prefix when you call an operator overload for example. For example std::string operator+(const std::string&,const std::string&). You could write
std::string a,b;
auto c = std::operator+(a,b);
but you don't. You are used to write
auto c = a + b;
And this only works due to ADL.
PPS: Even for std::swap its not right that it "should not be prefixed with std::". As outlined above, sometimes you do want to make use of ADL and sometimes you don't. That decision is not per function, but per use case. If you write code that swaps two objects and for some reason you want to call std::swap and nothing else, then you call std::swap. If you want to make use of ADL then you make use of ADL.

What's the point of iter_swap?

I was just wondering, why would anybody write this:
std::iter_swap(i, k);
instead of this?
std::swap(*i, *k); // saved a few keystrokes!
Then I looked into the implementation of iter_swap, and of course it only uses swap instead of std::swap since we're already in namespace std, anyway. That leads me to the next question:
Why would anybody write this:
using std::swap;
swap(a, b);
instead of this?
std::iter_swap(&a, &b); // saved an entire line of code!
Are there any important differences/issues I am overlooking here?
From the SGI docs (here):
[1] Strictly speaking, iter_swap is redundant. It exists only for technical reasons: in some circumstances, some compilers have difficulty performing the type deduction required to interpret swap(*a, *b).
To answer your second question, the using + swap allows the compiler to use user-defined swap functions that may be more efficient than the default implementation (by using ADL). Explicitly saying std::swap inhibits ADL and any custom swap methods it maybe have been able to find.
As for iter_swap it's presumably there to use in templates and clearly indicate intention rather than a swap that might indicate you expect a pointer.

Regarding the global namespace in C++

In C++, should we be prepending stuff in the global namespace with ::?
For example, when using WinAPI, which is in C, should I do ::HANDLE instead of HANDLE, and ::LoadLibrary instead of LoadLibrary? What does C++ say about this? Is it generally a good idea, factoring in issues like readability and maintainability?
Names in C++ can be qualified and unqualified. There are different rules for qualified and unqualified name lookup. ::HANDLE is a qualified name, whereas HANDLE is an unqualified name. Consider the following example:
#include <windows.h>
int main()
{
int HANDLE;
HANDLE x; //ERROR HANDLE IS NOT A TYPE
::HANDLE y; //OK, qualified name lookup finds the global HANDLE
}
I think that the desicion of choosing HANDLE vs. ::HANDLE is a matter of coding style. Of course, as my example suggests, there might be situations where qualifying is mandatory. So, you might as well use :: just in case, unless the syntax is somewhat disgusting for you.
As namespaces don't exists in C, don't use ::HANDLE to access HANDLE type.
Using the prepending :: for global namespace is a good idea for readability, you know the type you want to access is from global namespace.
Moreover, if you are in a nested namespace and declare your own HANDLE type (for example), then the compiler will use this one instead of windows.h one!
Thus, always prefer using :: before names when working in nested namespace.
The main point of interest is what the differences are from the point of view of the compiler, as it has already been said, if you include the :: then you are using qualified lookup, rather than unqualified lookup.
The advantage of using qualified lookup is that it will be able to pinpoint a particular symbol always. The disadvantage is that it will always pinpoint that particular symbol --i.e. it will disable Argument Dependent Lookup. ADL is a big and useful part of the language, and by qualifying you effectively disable it, and that is bad.
Consider that you had a function f in the global namespace, and that you added a type T inside namespace N. Not consider that you wanted to add an overload of f that would take a T as argument. Following the interface principle, you can add f to the N namespace, as f is actually an operation performed on T, and it so belongs with the type. In this case, if you had code that called (consider generic code) ::f(obj) on an object of unknown type U the compiler will not be able to pick up ::N::f(obj) as a potential overload as the code is explicitly asking for an overload in the global namespace.
Using unqualified lookup gives you the freedom of defining the functions where they belong, together with the types that are used as arguments. While it is not exactly the same, consider the use of swap, if you qualify std::swap then it will not pick up your hand rolled void swap( T&, T& ) inside your N namespace...
I would only fully qualify identifiers when the compiler would otherwise not pick up the element I want.
It's largely a matter of style; there are no performance or efficiency concerns to speak of. It can be a good practice on large projects and projects intended to be compiled on many different platforms, as under these circumstances collisions between global names and names in a namespace are more likely to occur.
Normally, you do not have to prepend :: for the global namespace. (Only in some really rare circumstances). IMHO it harms readability, but, on the other hand it probably won't break your code
I put all of my code into a namespace, and I tend to prefer the C++ headers over the C headers, so the only symbols left in the global namespace tend to be from the Windows API. I avoid pulling symbols from other namespaces into the current namespace (e.g., I never have using namespace std;), preferring instead to qualify things explicitly. This is in line with Google's C++ style guide.
I've therefore gotten into the habit of qualifying WinAPI function calls with :: for a few reasons:
Consistency. For everything outside the current namespace, I refer to it explicitly (e.g., std::string), so why not refer to the Windows APIs explicitly (e.g., ::LoadLibraryW)? The Windows APIs namespace is the global namespace.
A lot of the WinAPI functions are named generically (e.g., DeleteObject). Unless you're very familiar with the code you're reading, you may not know whether DeleteObject is a call to something in the current namespace or to the Windows API. Thus, I find the :: clarifies.
A lot of Windows frameworks have methods with the same names as the raw calls. For example, ATL::CWindow has a GetClientRect method with a slightly different signature than WinAPI's GetClientRect. In this framework, it's common for your class to be derived from ATL::CWindow, so, in your class's implementation, it's normal to say GetClientRect to invoke the inherited ATL method and ::GetClientRect if you need to call the WinAPI function. It's not strictly necessary, since the compiler will find the right one based on the signature. Nevertheless, I find that the distinction clarifies for the reader.
(I know the question wasn't really about WinAPI, but the example was in terms of WinAPI.)
No, if you do not have a LoadLibrary method in your class you do not need to use the global scope. In fact, you should not use global scope because if you later on add a LoadLibrary to your class your intentions is probably to override the global function...

How important is consistent usage of using declarations?

Most of the research I've done on the use of using declarations, including reading relevant sections of various style guides, indicates that whether or not to use using declarations in C++ source files, as long as they appear after all #includes, is a decision left to the coder. Even the style guides I read, which usually come down on one side or the other of such common disputes for the sake of consistency, are fairly flexible in this regard.
My question is, given this high degree of flexibility, how important is it to use a consistent style? For example, suppose an author wrote something like
using std::vector;
vector<T> v;
std::cout << v[0] << std::endl;
Is the inconsistent application of using on std::vector but not std::cout or std::endl generally considered acceptable, or would it be considered undisciplined?
I think the whole point of using is that you use it inconsistently among names. Names you need very frequently in some block can be declared locally with a using declaration, while others are not. I don't see a problem with that.
Declaring a name to have namespace scope is always much harder to take. I think if the name clearly is known to belong to a particular namespace so that confusing it with other namespaces won't occur, It won't hurt to put a using declaration if it makes your code more readable.
I am now a strong proponent for explicitly stating the namespace (ie no 'using')
Most peoples namespace history goes like this (in non trivial, >100kloc projects)
Innocence -> style 1
using namespace std;
Ouch -> style 2
using std::string;
using std::vector;
OK, enough already -> style 3
std::string foo = "xxx";
Assuming you don't say using namespace std; anywhere, I don't think most developers care one way or another in other people's code. The only thing that might bother them is the overuse of the std:: qualifier --- that is if you're saying "std::vector" 20 times in the function, maybe it's time for a "using std::vector". Otherwise, no one should care.
Sometimes, in my own code, I'll use the "std::" qualifier specifically to indicate that this is the only place that I'm using that identifer.
I try for not using using (no pun intended).
For saving typing, I like to do typedefs, e.g.:
typedef std::vector< int > IntVector;
typedef std::vector< Foo > FooVector;
This is less an answer than a counterpoint to a few other answers that have advocated always explicitly including the namespace as part of the name. At times, this is a poor idea. In some cases, you want to use a name that's been specialized for the type at hand if it exists, but use a standard-provided alternative otherwise.
As a typical example, let's consider a sort function. If you're sorting some objects of type T, you're going to end up swapping items. You want to use a special swap(T &, T&) if it exists, but template <class T> std::swap otherwise.
If you try to specify the full name of the swap you're going to use explicitly, you have to specify one or the other -- either you specify a specialized version, and instantiating your sort over a type that doesn't define it's own swap will fail, or else you specify std::swap, and ignore any swap that's been provided specifically for the type you're sorting.
using provides a way out of this dilemma though:
using namespace std;
template <class T>
mysort(/* ... */ ) {
// ...
if (less(x[a], x[b])
swap(x[a], x[b]);
// ...
}
Now, if the namespace in which T is found contains a swap(T &, T&), it'll be found via argument dependent lookup, and used above. If it doesn't exist, then std::swap will be found (and used) because the using namespace std; made it visible as well.
As an aside, I think with one minor modification, using namespace x; could be made almost entirely innocuous. As it stands right now, it introduces the names from that namespace into the current scope. If one of those happens to be the same as a name that exists in the current scope, we get a conflict. The problem, of course, is that we may not know everything that namespace contains, so there's almost always at least some potential for a conflict.
The modification would be to treat using namespace x; as if it created a scope surrounding the current scope, and introduced the names from that namespace into that surrounding scope. If one of those happened to be the same as a name introduced in the current scope, there would be no conflict though -- just like any other block scoping, the name in the current scope would hide the same name from the surrounding scope.
I haven't thought this through in a lot of detail, so there would undoubtedly be some corner cases that would require more care to solve, but I think the general idea would probably make a lot of things quite a bit simpler anyway.

Should every class have its own namespace?

Something that has been troubling me for a while:
The current wisdom is that types should be kept in a namespace that only
contains functions which are part of the type's non-member interface (see C++ Coding Standards Sutter and Alexandrescu or here) to prevent ADL pulling in unrelated definitions.
Does this imply that all classes must have a namespace of their own? If
we assume that a class may be augmented in the future by the addition of
non-member functions, then it can never be safe to put two types in the
same namespace as either one of them may introduce non-member functions
that could interfere with the other.
The reason I ask is that namespaces are becoming cumbersome for me. I'm
writing a header-only library and I find myself using classes names such as
project::component::class_name::class_name. Their implementations call
helper functions but as these can't be in the same namespace they also have
to be fully qualified!
Edit:
Several answers have suggested that C++ namespaces are simply a mechanism for avoiding name clashes. This is not so. In C++ functions that take a parameter are resolved using Argument Dependent Lookup. This means that when the compiler tries to find a function definition that matches the function name it will look at every function in the same namespace(s) as the type(s) of its parameter(s) when finding candidates.
This can have unintended, unpleasant consequences as detailed in A Modest Proposal: Fixing ADL. Sutter and Alexandrescu's rule states never put a function in the same namespace as a class unless it is meant to be part of the interface of that class. I don't see how I can obey that rule unless I'm prepared to give every class its own namespace.
More suggestions very welcome!
No. I have never heard that convention. Usually each library has its own namespace, and if that library has multiple different modules (e.g. different logical units that differ in functionality), then those might have their own namespace, although one namespace per library is sufficient. Within the library or module namespace, you might use namespace detail or an anonymous namespace to store implementation details. Using one namespace per class is, IMHO, complete overkill. I would definitely shy away from that. At the same time, I would strongly to urge you to have at least one namespace for your library and put everything within that one namespace or a sub-namespace thereof to avoid name clashes with other libraries.
To make this more concrete, allow me to use the venerable Boost C++ Libraries as an example. All of the elements within boost reside in boost::. There are some modules within Boost, such as the interprocess library that have its own namespace such as boost::interprocess::, but for the most part, elements of boost (especially those used very frequently and across modules) simply reside in boost::. If you look within boost, it frequently uses boost::detail or boost::name_of_module::detail for storing implementation details for the given namespace. I suggest you model your namespaces in that way.
No, no and a thousand times no! Namespaces in C++ are not architectural or design elements. They are simply a mechanism for preventing name clashes. If in practice you don't have name clashes, you don't need namespaces.
To avoid ADL, you need only two namespaces: one with all your classes, and the other with all your loose functions. ADL is definitely not a good reason for every class to have its own namespace.
Now, if you want some functions to be found via ADL, you might want to make a namespace for that purpose. But it's still quite unlikely that you'd actually need a separate namespace per class to avoid ADL collisions.
Probably not. See Eric Lippert's post on the subject.
Couple things here:
Eric Lippert is a C# designer, but what he's saying about bad hierarchical design applies here.
A lot of what is being described in that article has to do with naming your class the same thing as a namespace in C#, but many of the same pitfalls apply to C++.
You can save on some of the typedef pain by using typedefs but that's of course only a band-aid.
It's quite an interesting paper, but then given the authors there was a good chance it would be. However, I note that the problem concerns mostly:
typedef, because they only introduce an alias and not a new type
templates
If I do:
namespace foo
{
class Bar;
void copy(const Bar&, Bar&, std::string);
}
And invoke it:
#include <algorithms>
#include "foo/bar.h"
int main(int argc, char* argv[])
{
Bar source; Bar dest;
std::string parameter;
copy(source, dest, parameter);
}
Then it should pick foo::copy. In fact it will consider both foo::copy and std::copy but foo::copy not being template will be given priority.