C++边边角角(一)

#include <stdio.h>
#include <stdlib.h>
struct A
{
    int a;
    int b;
    int c;
    A() {a=0; printf("A()/n");}
    A(int _a) {a=_a;}
    ~A() {printf("~A()/n");}

    void *operator new[](unsigned int s)
    // 无论如何 's'传递的是大小,而不是数组元素个数
    // gcc编译环境下这个值是 sizeof((n) * sizeof(A))+4,
    // 估计这4字节用来作为起始保留

    // 这样delete[]也需对应实现      
    {
        int n = (s-4)/sizeof(A);
        printf("new[](int n) ... %d, %d/n", s, n);
        return ((char*)malloc(s) + 4); // ex-handling omitted
    }
    void*operator new(unsigned int s, A*p)
    {
        int n = (s+sizeof(A))/sizeof(A);
        printf("new[](unsigned int s, A*p) ... %d,%d/n", s, n);
        for (int i = 0; i < n; i++)
        {
            p[i].~A();
        }
        return (void*)p;
    }
    void*operator new[](unsigned int s, A*p)
    {
        int n = (s-4)/sizeof(A);
        printf("new(unsigned int s, A*p) ... %d,%d/n", s, n);
        for (int i = 0; i < n; i++)
        {
            p[i].~A();
        }
        return (void*)p;
    }
};
int main(void)
{
    //由`A'指示调用new ...(..., A*p)系列
    A *pa = new A[32];
    A *pp = new (pa) A[16]; //看似很不错的机制,ICOM指出在含virtual function继承情形下这个足以制造C++语言矛盾
    A *p2 = new (pa) A(2);    
    for (int i = 0; i < 32; i++)
    {
        printf("a[%d]=%d/n", i, pa[i].a);
    }
    return 0;
}

posted @ 2008-09-05 01:30  quanben  阅读(133)  评论(0编辑  收藏  举报