troubleshooting Question

Placement new queries

Avatar of mrwad99
mrwad99Flag for United Kingdom of Great Britain and Northern Ireland asked on
C++
18 Comments2 Solutions540 ViewsLast Modified:
Ah hello.

Firstly, seasons greetings to one and all!

Now, please consider the following code, from http://www.glenmccl.com/nd_cmp.htm

      int flag = 0;

        typedef unsigned int size_t;

        void operator delete(void* p, int i)
        {
                flag = 1;
        }

        void* operator new(size_t s, int i)
        {
                return new char[s];
        }

        class A {
        public:
                A() {throw -37;}
        };

        int main()
        {
                try {
                        A* p = new (1234) A;
                }
                catch (int i) {
                }
                if (flag == 0)
                        return 1;
                else
                        return 0;
        }

Now, at the very bottom of the article, we have "Note also that you can't call overloaded operator delete directly via the operator syntax; you'd have to code it as a regular function call.".

OK.  So, if I ammend the code above, so the first thing before the try/catch block is

      int* n = new ( 100 ) int;
      //operator delete ( n, 100 );
      delete n;

1) I find that the normal delete call works fine; that being the case, what is the statement shown above all about??

2) The first lot of code shown above does not have anything that actually does the freeing of memory, we just set flag to be 1.  So am I correct in thinking that I should ammend this to be

        void operator delete(void* p, int i)
        {
            free ( p );      // NEW LINE!
                flag = 1;
        }

Or should I use delete?  Which is correct?  I have noted that delete calls into free() anyway, but as the rule goes we should always use new/delete and malloc/free etc...

TIA
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 2 Answers and 18 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 2 Answers and 18 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros