Are there any problems with this overload of the new operator?

I was thinking about some memory pools / allocation materials that I could write, so I came up with this overload operator newthat I want to use to facilitate memory reuse. I am wondering if there are any problems you guys can come up with with my implementation (or any other possible ones).

#include <cstddef>

namespace ns {
    struct renew_t { };
    renew_t const renew;
}

template<typename T>
inline void * operator new(std::size_t size, T * p, ns::renew_t renew_constant) {
    p->~T();
    return p;
}

template<typename T>
inline void operator delete(void *, T *, ns::renew_t renew_constant) { }

It can be used as

int main() {
    foo * p(new foo());        // allocates memory and calls foo default constructor
    new(p, ns::renew) foo(42); // calls foo destructor, then calls another of foo constructors on the same memory
    delete p;                  // calls foo destructor and deallocates the memory
}
+3
source share
3 answers

MUST be nice if you don't try something crazy and try updating the subclass. Since you said it was for the pool, everything should be fine.

, - ? , , - . , , .

: , , (p- > ~ T new (p) T()), , , , .

+1

http://www.gotw.ca/gotw/022.htm http://www.gotw.ca/gotw/023.htm.

, operator=, . operator new ( operator delete, YUCK!) .

, Cibbor Herb Sutter , operator=.

+2

delete() , .

new(p, ns::renew) foo(42). .

, , , , . " " .

// Not exception safe!

void* p = ::operator new(sizeof(T)); // allocate raw memory

new(p) T(41); // construct a T at this memory location
p->~T();      // destruct T

new(p) T(42); // recreate a different T at the same memory location
p->~T();      // destruct T

::operator delete(p); // deallocate raw memory

MemoryPool.

Of course, this only applies if you are really dealing with memory directly to implement a real memory pool or container allocator. In other situations, you'd better overload the operator =() proposed by Potatoswatter .

0
source

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


All Articles