Sign in to follow this  
maya18222

c++ new

Recommended Posts

is it possible to do something like this?
#include <iostream>
using namespace std;

namespace MyNew{
	void* operator new(size_t size){
		cout << "Allocating : "<< size << " bytes/n";
		void* p = ::operator new(size);	//call global new op
		return  p;
	}
}


int main()
{
	int* i = MyNew::operator new int();	//call my new op
	getchar(); 
}

//errors
Error	1	error C2440: 'initializing' : cannot convert from 'void *(__cdecl *)(size_t)' to 'int *'	
Error	2	error C2144: syntax error : 'int' should be preceded by ';'	


Share this post


Link to post
Share on other sites
A working call would look like this:


int* i = (int*)MyNew::operator new(sizeof(int)); //call my new op


But if you are willing to go to these lengths, why not so:


#include <iostream>

template <class T>
T* MyNew(const T& t = T())
{
std::cout << "Allocating : "<< sizeof(T) << " bytes\n";
return new T(t);
}

int main()
{
int* i = MyNew<int>();
}

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this