Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overloading operator new

Tags:

c++

I am overloading operator new as below

class A {
public:
    void* operator new(size_t) { return (void*) Buf; }
};

I am getting "declaration of operator new as non-function error" when I try to compile. Could someone help me with this?

like image 979
leslieg Avatar asked May 06 '11 09:05

leslieg


People also ask

Can new operator be overloaded?

New and Delete operators can be overloaded globally or they can be overloaded for specific classes. If these operators are overloaded using member function for a class, it means that these operators are overloaded only for that specific class.

What is :: operator new?

The new operator invokes the function operator new . For arrays of any type, and for objects that aren't class , struct , or union types, a global function, ::operator new , is called to allocate storage. Class-type objects can define their own operator new static member function on a per-class basis.

Can I create new operator using operator overloading in C++?

Things to Remember in C++ Operator OverloadingWe do not need to create an operator function. Operator overloading cannot change the precedence and associativity of operators. However, if we want to change the order of evaluation, parentheses should be used. There are 4 operators that cannot be overloaded in C++.

How is new operator implemented C++?

When new is used to allocate memory for a C++ class object, the object's constructor is called after the memory is allocated. Use the delete operator to deallocate the memory allocated by the new operator. Use the delete[] operator to delete an array allocated by the new operator.


1 Answers

Have you size_t be defined? You need to include stddef.h for it. But better you include cstddef and use std::size_t.

Your declaration otherwise looks fine, apart from the semantics of always returning Buf being screwed up. The operator new should return a buffer of the size specified as the first argument.

like image 85
Johannes Schaub - litb Avatar answered Oct 11 '22 09:10

Johannes Schaub - litb