Mailing Lists: Apple Mailing Lists
Image of Mac OS face in stamp
problem overriding operator new/delete and std stream
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

problem overriding operator new/delete and std stream



I'm trying to replace global operator new and delete with my own
versions, but there's a problem with std stream classes.  When I new
up an ostringstream, my version of new is used, but when I delete it,
seems the libstdc++ version of delete is being used.  Any clues?

Thanks.
Elron

#include <new>
#include <sstream>
#include <cstdio>

void* operator new(std::size_t size)
{
	std::printf("my new\n");
	if (size == 0)
		size = 1;

	void* rawMem = std::malloc(size + 16);
	if (rawMem == 0)
		throw std::bad_alloc();
	return rawMem;
}
void* operator new[](std::size_t size)
{
	std::printf("my new[]\n");
	if (size == 0)
		size = 1;

	void* rawMem = std::malloc(size + 16);
	if (rawMem == 0)
		throw std::bad_alloc();
	return rawMem;
}

void operator delete(void* ptr) throw()
{
	std::printf("my delete\n");
	if (ptr)
		std::free(ptr);
}
void operator delete(void* ptr, const std::nothrow_t&) throw()
{
	std::printf("my delete nothrow\n");
	if (ptr)
		std::free(ptr);
}
void operator delete[](void* ptr) throw()
{
	std::printf("my delete[]\n");
	if (ptr)
		std::free(ptr);
}
void operator delete[](void* ptr, const std::nothrow_t&) throw()
{
	std::printf("my delete[] nothrow\n");
	if (ptr)
		std::free(ptr);
}

struct foo
{
	foo() { std::printf("foo()\n"); }
	~foo() { std::printf("~foo()\n"); }
};

int main (int argc, char * const argv[]) {

	foo* f = new foo;
	delete f;

	std::ostringstream* s = new std::ostringstream;
	delete s;

    return 0;
}

Output:
my new
foo()
~foo()
my delete
my new

Debugger stopped.
Program exited with status value:0.
 _______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list      (email@hidden)
Help/Unsubscribe/Update your Subscription:

This email sent to email@hidden



Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Contact Apple | Terms of Use | Privacy Policy

Copyright © 2011 Apple Inc. All rights reserved.