#include <iostream> template <class T> // (1) class B { public: void foo(T* t); // (2) }; class T // (3) { public: int i; }; void B<T>::foo(T* t) // (4) { std::cout << t->i << std::endl; } int main() { B<T> b; // (5) T t; t.i = 3; b.foo(&t); }
Tuesday, March 15, 2011
Simple c++ question. Is "T" class or template?
Thursday, March 10, 2011
Sunday, March 6, 2011
How to overload new and delete operator
void* __cdecl operator new(size_t size) { return malloc(size); } void __cdecl operator delete(void* p) { free(p); }
Wednesday, March 2, 2011
Where array count is stored when new[] is called?
[source code] #include <new> // for size_t #include <stdio.h> class A { public: A() {} virtual ~A() {} static void* operator new (size_t size) { void* res = ::operator new(size); printf("new return %p\n", res); return res; } static void operator delete (void *p) { printf("delete %p\n", p); ::operator delete(p); } static void* operator new[](size_t size) { void* res = ::operator new(size); printf("new[] return %p\n", res); return res; } static void operator delete[](void *p) { printf("delete[] %p\n", p); ::operator delete[](p); } }; void foo() { A* a = new A; printf("a= %p\n", a); delete a; } void bar() { A* a = new A[5]; printf("a= %p\n", a); delete []a; } int main() { foo(); printf("\n"); bar(); } [result] new return 00633B88 // same a= 00633B88 // same delete 00633B88 // same new[] return 00631A90 a= 00631A94 // 4 byte skipped !!! delete[] 00631A90
When new[] is called, you can figure out that array count value(5) is stored prior to new[] operator return pointer value(4 bytes offset in the above result). Of course(as you guess), when delete[] is called, the count value is used to delete all allocated objects.
Subscribe to:
Posts (Atom)