3

Why is there a sort function in the global namespace in C++? Why this code compiles?

#include <iostream>
#include <vector>

int main() {
    std::vector<int> array(10);
    sort(array.begin(), array.end());
}

PS: clang++ --std=c++11 --stdlib=libc++ ./test.cpp

0

1 Answer 1

7

sort isn't in the global namespace, it's in std. However, the result type of vector::begin() may be in std too (this is implementation-dependent). If so then std::sort is found by ADL (argument-dependent lookup).

If you don't want std::sort to be found by ADL then you can make a qualified call to sort instead of an unqualified one: ::sort(array.begin(), array.end()).

11
  • 2
    BTW: This seems to be a good description of ADL: en.cppreference.com/w/cpp/language/adl
    – Joe Z
    Nov 3, 2013 at 14:06
  • 2
    @SukhanovNiсkolay if your sort is in the global namespace, you can call it with ::sort(args);. But I suggest you put it in your own namespace. Nov 3, 2013 at 14:10
  • 1
    @SukhanovNiсkolay No, ADL works because the arguments (A) are in the std namespace. Nov 3, 2013 at 14:16
  • 2
    @SukhanovNiсkolay Good point. It must be brought in by either of your two includes. Of course, you can't rely on that, it is a feature of this implementation. Nov 3, 2013 at 14:18
  • 2
    @kerreksb not really. esp in debug, adding checks for UB is worth it. And in release, slightly less than naked pointers gives you a more consistent compile result to debug. Nov 3, 2013 at 15:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.