Is the behaviour of this code defined?
int* ptr = new int[10];
operator delete[] (ptr, 0);
This code compiles fine and (on my machine) it seems nothing is happening. Is its the behaviour defined somewhere?
Is the behaviour of this code defined?
int* ptr = new int[10];
operator delete[] (ptr, 0);
This code compiles fine and (on my machine) it seems nothing is happening. Is its the behaviour defined somewhere?
This answer is aimed at most C++ software developers, not so much at language-lawyer types who want the formal official answer.
The delete[](ptr, 0)
call has no strong reason for the standard committee to define behavior for. Also, even if such a behavior were to be defined - there is no single obvious behavior we would expect:
delete[](ptr)
or delete[](ptr, 10)
.It is not a good idea for your code to rely on such a choice, even if the standards committee had made it. It would make your code difficult to understand and easy to break - for somebody else, or even for yourself, a few years down the line.
That's why it doesn't really matter whether the behavior here is defined, and you should absolutely avoid such a statement.
See also :
new
and delete
explicitly.In this statement
operator delete[] (ptr, 0);
there is called explicitly the deallocation function
void operator delete[](void*, std::size_t) noexcept;
The second parameter in the call that has the type size_t
is just set to 0.
The behavior of the call then the second parameter is equal to 0 is undefined provided that when the allocated memory was not have the size equal to 0.
delete[](ptr, 0)
(without the operator
keyword). Now the OP is calling the operator function directly. –
Carlenacarlene f(1, 2)
is not equivalent to f(2)
. Here f
is operator delete[]
. –
Hege © 2022 - 2024 — McMap. All rights reserved.
operator delete
andoperator delete[]
reference should be helpful. Exact which overload you're calling is hard to say though. – Carlenacarleneptr
and discards the result, then passes0
(an invalid address) to delete – Speculation