Re: Is new observable behavior?
On Apr 1, 2:54 pm, Chris <cuz...@gmail.com> wrote:
On Apr 1, 12:04 pm, Edward Rosten <Edward.Ros...@gmail.com> wrote:
Is a call to new and delete observable behavior? Is the compiler free
to optimize:
int test_new_optimization(int i)
{
int* tmp = new int;
*tmp = i;
int j = *tmp;
delete tmp;
return j;
}
into:
int test_new_optimization(int i)
{
return i;
}
#include <iostream>
#include <cstdlib>
void * operator new(std::size_t size) {
std::cerr << "Observable? (new)" << std::endl;
return std::malloc(size);
}
void operator delete(void * ptr) {
std::cerr << "Observable? (delete)" << std::endl;
std::free(ptr);
}
...
Here's the output:
./a.out
Observable? (new)
Observable? (delete)
test_new_optimization(3) is `3'
Thus, it's observable.
These two particular implementations of new() and delete() have
observable behavior. In general, though, new() and delete() do not
perform any I/O or have any other kind of observable behavior. So the
answer to the original question, is - for all practical purposes -
"yes" - the compiler will almost certainly be free to eliminate the
calls to new() and delete().
Assuming that my operator overloads did
something important in addition to just allocating/releasing
memory, I would be unhappy to discover that the compiler didn't
actually call them.
If the overloaded functions have no observable behavior - then there
would be no way for you to discover whether or not the program
actually called them.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]