Reputation: 3765
I am reading the source code of SGI standard template library. I find that the operator new
function always has a double-colon in front of it. Like this:
T* tmp = (T*)(::operator new((size_t)(size * sizeof(T))));
operator new
can be directly called without adding the ::
field, then why do the stl coders write it in this way? What trap or situation may it come to if we don't use the ::
in front of them.
Upvotes: 13
Views: 504
Reputation: 3460
You can overload operator new for a class and prefixing it with "::" will call the global "default" operator new instead of a possible overload. For example:
#include <iostream>
class Foo
{
public:
Foo() { std::cout << "Foo::Foo()" << std::endl; }
void * operator new(size_t )
{
std::cout << "Foo::operator new()" << std::endl;
return static_cast<Foo *>(malloc(sizeof(Foo)));
}
};
int main()
{
Foo foo;
std::cout << "----------------------" << std::endl;
Foo * p = new Foo;
std::cout << "----------------------" << std::endl;
Foo * q = ::new Foo;
}
will print
Foo::Foo()
----------------------
Foo::operator new()
Foo::Foo()
----------------------
Foo::Foo()
Edit: The code snipped is indeed not about operator new that is defined in a class scope. A better example would be this:
#include <iostream>
namespace quux {
void * operator new(size_t s)
{
std::cout << "quux::operator new" << std::endl;
return malloc(s);
}
void foo()
{
std::cout << "quux::foo()" << std::endl;
int * p = static_cast<int*>(operator new(sizeof(int)));
}
void bar()
{
std::cout << "quux::bar()" << std::endl;
int * p = static_cast<int*>(::operator new(sizeof(int)));
}
} // namespace quux
int main()
{
quux::foo();
quux::bar();
}
which prints
quux::foo()
quux::operator new
quux::bar()
Upvotes: 8
Reputation: 135
Double-colon is used to prevent T::operator new() to be called (if defined).
Upvotes: 0
Reputation: 114529
::operator new
in C++ is the global memory allocator that is called every time a certain amount of bytes is needed for a single object. Note that the return value is a void *
and that ::operator new(size_t)
deals with raw bytes, not objects.
It is basically the C++ counterpart of malloc
with simply a funny name.
A separate global allocator ::operator new[](size_t sz)
is instead used to allocate memory for arrays of objects.
These two operators, their counterparts ::operator delete
and ::operator delete[]
and also the nothrow
version of the allocators are used for all memory needs of the C++ runtime.
They may be implemented in terms of calls to malloc
/free
or not. What is guaranteed is that malloc
and free
dont use them (thus you can call malloc
and free
if you want to reimplement these functions without the risk of infinite recursion).
Upvotes: 1
Reputation: 35408
To call the operator new
from the global namespace, in case the user (or someone) else decided to have a new
operator.
Upvotes: 0