1

I am pretty much sure it is but if I am interpreting correctly the standard (Section 18.6.1.2 new.delete.array) mentions that:

void operator delete[](void* ptr) noexcept; pointer.

. 13 Default behavior: Calls operator delete(ptr)

Since in its default behavior delete[] just calls its delete(ptr) equivalent why should it matter which version is called? I tried with a sample code to verify this and it crashes making it more evident that mismatching new[] and delete indeed lead to bad things

#include <iostream>
#include <memory>
class foo{
    public:
        void bar(){
            std::cout << "foo's bar" << std::endl;
        }
        ~foo(){
            std::cout << "foo dies after this" << std::endl;
        }
};
int main() {
    std::shared_ptr<foo> x(new foo[10]);
    return 0;
}

How should the above quoted line from the standard be interpreted?

Community
  • 1
  • 1
bashrc
  • 4,725
  • 1
  • 22
  • 49
  • 1
    Related - http://stackoverflow.com/questions/13061979/shared-ptr-to-an-array-should-it-be-used – Luchian Grigore May 06 '15 at 08:41
  • 2
    `delete` does more than calling `::operator delete`, and `delete[]` does more than calling `::operator delete[]`. It's unclear to me whether you understand this. If you do, can you please edit your question to address it? –  May 06 '15 at 08:42
  • @LuchianGrigore I am aware of the nuisance of creating shared_ptr that way. Infact that is why I have explicitely chosen that example. My main question is around interpreting the language standard. – bashrc May 06 '15 at 08:43
  • 1
    It is accurate, it describes the operation of the *library function*. Calling the destructor of all the array elements is the job of the compiler, not the library function. – Hans Passant May 06 '15 at 08:47

1 Answers1

7

You're confusing the delete[] expression with the function operator delete[]. When you write:

delete[] p;

then the compiler issues code which will call destructors for all objects in the array pointed to by p, and then call the deallocation function operator delete[] with the argument p. As per the documentation you've quoted, the default ::operator delete[] calls ::operator delete. So the following calls to the deallocation functions are equivalent when default implementations are used:

::operator delete[] (p);
::operator delete(p);

But the following are not equivalent, because they do much more than just call the deallocation functions:

delete[] p;
delete p;
Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455