Why should we use the "::" operator for global functions / objects?

I saw how it was used in different places. C ++ programmers often use the :: operator before calling a global function.

eg

::glGenBuffers( 1, &id );

Why is this? Why not just use:

glGenBuffers( 1, &id );
+4
source share
6 answers

To avoid accidental namespace collisions. For example, if the current namespace is glGenBufferssomething different from "good" glGenBuffersto ::, you can specify that the trigger glGenBuffers, which is in the global namespace.

+4
source

, 1) 2) .

()

#include <algorithm>

using namespace std;

void swap( int &x, int &y )
{
   int tmp = x;
   x = y;
   y = tmp;
}

int main()
{
   int x = 5, y = 10;

   //swap( x, y ); compiler error: what function to call?

   ::swap( x, y ); // the user defined function is called

   std::swap( x, y ); // the standard function is called.
}

#include <iostream>

void f() { std::cout << "::f()\n"; }

namespace MyNamespace
{
   void f() { std::cout << "MyNamespace::f()\n"; }

   void g() { f(); } // calls MyNamespace::f()

   void h() { ::f(); } // calls ::f()
}


int main()
{
   MyNamespace::g();
   MyNamespace::h();
}
+2

C++:

:: ( ) . , .

+1

::glGenBuffers,

void method()
{
    std::cout << "method in global namespace";
}

class Test {
    void method() 
    {
        std::cout << "method in Test class";
    }

    void test()
    {
        method(); // method in Test class
        ::method(); //method in global namespace
    }
}
+1

. , :

namespace foo
{
  class X {};
  void bar(X*, int):
}

// ... much in between ...

foo::X some_object

// ... more in between ...

void bar(X*, long);

int main()
{
  bar(&some_object, 42); // calls foo::bar, because it is a better match
  ::bar(&some_object, 42); // calls ::bar, because it is explicitly told to
}

, bar foo some_object foo, foo::bar ::bar .

+1

(::) 2 :

a) //typedef ( ) :

int fun()
    {
    return 1;
    }

namespace x
    {
    using ::fun; 
    // you cannot do `using fun`, as using requires a namespace after
    // in this case, we are `using` the global namespace
    }

int main()
    {
    std::cout << fun() + x::fun(); // prints 2
    }

. STL, : std::size_t:

typedef unsigned int size_t;

namespace std
    {
    using ::size_t;
    }

size_t x = 1;
std::size_t y = 2;

b) :

# include <algorithm>

using namespace std;

template<class T> inline
    void swap(T &left, T &right)
    {
    T tmp = left;
    left = right;
    right = tmp;
    }

int main()
    {
    int a = 1, b = 2;
    // swap(a, b) - error: which 'swap'?
    std::swap(a, b); // the one in <algorithm>
    ::swap(a, b); // the one i defined
    }
  • Note: using namespace std;not recommended practice.

Edit

The MSVC compiler provides macro _CSTD( #define _CSTD ::), so you can use using _CSTD fun;, etc if you want.

0
source

Source: https://habr.com/ru/post/1533227/


All Articles