M. Christopher
M. Christopher

Reputation: 321

C++: Overloaded New call constructs object automatically

I'm trying to overload the new operator in order to allocate my own memory, but I still need to construct the object. That's why I decided to pass the parameters through a variadic template in order to feed the object's constructor properly.

The constructor is called twice in this example, I can't explain why. It seems that the overloaded new calls automatically the constructor.

#include <stdlib.h>
#include <iostream>
#include <new>

class A
{
public:
  template<typename... Args>
  void *operator new(size_t sz, Args ...parameters)
  {
    void *mem = ::operator new(sizeof(A));
    A *var = ::new (mem) A(parameters...);
    return var;
  }
  A() : num(0) { std::cout << "Default" << std::endl; }
  A(int nb) : num(nb) { std::cout << "Integer = " << num << std::endl; }
  const int num;
};

int main()
{
  A *obj = new A(3);
  std::cout << "Obj result = " << obj->num << std::endl;
}

Upvotes: 2

Views: 68

Answers (2)

user5301649
user5301649

Reputation: 21

I'm trying to overload the new operator in order to allocate my own memory, but I still need to construct the object.

No you don't. operator new by definition initializes the object. See [expr.new]/15:

A new-expression that creates an object of type T initializes that object as follows:

— If the new-initializer is omitted, the object is default-initialized (8.5); if no initialization is performed, the object has indeterminate value.

— Otherwise, the new-initializer is interpreted according to the initialization rules of 8.5 for direct-initialization.

At a minimum, your overload can look like this:

void *operator new(size_t sz)
{
    return ::operator new(sizeof(A));
}

The static keyword is optional.

Upvotes: 0

M. Christopher
M. Christopher

Reputation: 321

Fixed, there is not reason to try to call the constructor within the overload, the object will be constructed at returned void*'s pointed allocated memory.

Upvotes: 2

Related Questions