How can I overload the new operator to allocate on the stack?

How can I overload the new operator for a class type so that it allocates the memory on the stack instead of heap (basically so that the user doesn't have to call delete afterwards).

What about something like this:

class A{
    private:
        A(int i):
           this->i(i);
        {}
        A a;
        int i;

    public:
        void* operator new(size_t sz){
            a(12);
        }
};

Would the above solution work?


Don't!

Use automatic storage...

The new operator is designed to implement dynamic allocation (what you are calling "on the heap") and, although you can provide your own allocator, as such you cannot twist it into obeying the scoping rules of objects of automatic storage duration (what you are calling "on the stack").

Instead, write:

MyType myobject;  // automatic storage duration

...or smart pointers...

Or, if you don't mind dynamic storage duration but only want to avoid later manual destruction, use smart pointers:

std::unique_ptr<MyType> myptr(new myobject());  // unique, dynamic storage duration
std::shared_ptr<MyType> myptr(new myobject());  // shared, dynamic storage duration

Both of these are found in C++11 ( std:: ) and Boost ( boost:: ).

... or placement new ?

Another approach might be placement new but this is a dark and dangerous path to travel that I would certainly not recommend at this stage. Or, frankly, any stage... and you'd usually still need to do manual destruction. All you gain is using the keyword new , which seems pointless.


I think the good answer here is:

Don't overload operator new.

If you still want to go through that road, you can look at this question.

If not, you can always use smart pointers or shared pointers to avoid users having to delete allocated memory.


Why not just automatic variable (it is "on stack" and does not need to call destructor manually:

int foo() {
  A a;
  int i;
  ...
  // don't need to call delete

}


To answer your question literally, there is placement new, which takes memory from user - so you can have this memory as automatic buffer:

  alignas(int) char buffer[sizeof(int)];
  int* p = new (buffer) int;
  //           ^^^^^^^^

For non POD object - you do not need to call delete - but you must call destructor by hand:

  class A { public: ~A(){} };
  alignas(A) char buffer[sizeof(At)];
  A* p = new (buffer) A;
  //         ^^^^^^^^
  p->~A();

alignas is new in C++11 - in C++03 you must deal with proper alignment somehow differently. Proper aligned memory must be returned from new - otherwise the behavior is undefined.

链接地址: http://www.djcxy.com/p/82480.html

上一篇: 堆腐败C ++

下一篇: 我该如何重载新操作符才能在堆栈上分配?