关于static_cast的一个问题?


一下代码是在读《提高C++性能的编程技术》遇到的一个问题,作者本意应该是把size字节大小的内存地址强制转化成NextOnFreeList类型,可编译器一直出错。

环境是:macbook pro 64位


 Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 5.0 (clang-500.2.79) (based on LLVM 3.3svn)
Target: x86_64-apple-darwin13.4.0
Thread model: posix

代码如下:


 #include <ctime>
#include <iostream>
#define MAN_TIMES 10000

using namespace std;

//// version 0.2
class NextOnFreeList{
public:
    NextOnFreeList *next;
};

class Rational{
public:
    Rational(int a = 0,int b = 1):n(a),d(b){};

    inline void *operator new(size_t size);
    inline void operator delete(void *doomed,size_t size);

    static void newMemPool() {expandTheFreeList();}
    static void deleteMemPool();
private:
    static NextOnFreeList *freeList;
    static void expandTheFreeList();
    enum {EXPANSION_SIZE = 32};

    int n;
    int d;
};
inline void* Rational::operator new(size_t size){
    if(0 == freeList){
        expandTheFreeList();
    }
    NextOnFreeList *head = freeList;
    freeList = head->next;

    return head;
}
inline void Rational::operator delete(void *doomed,size_t size){
    NextOnFreeList *head = static_cast<NextOnFreeList *>(doomed);

    head->next = freeList;

    freeList = head;
}

void Rational::expandTheFreeList(){
    size_t size = (sizeof(Rational) > sizeof(NextOnFreeList *))?sizeof(Rational):sizeof(NextOnFreeList *);
    //static_cast 老是报错,为什么啊?
    NextOnFreeList *runner = static_cast<NextOnFreeList *>(new char [size]);

    freeList = runner;

    for(int i = 0;i < EXPANSION_SIZE;i++){
        //static_cast 老是报错,为什么啊?
        runner->next = static_cast<NextOnFreeList*>(new char [size]);
        runner = runner->next;
    }
    runner->next = 0;
}
void Rational::deleteMemPool(){
    NextOnFreeList *nextPtr;
    for(nextPtr = freeList;nextPtr != NULL;nextPtr = freeList){
        freeList = freeList->next;
        delete []nextPtr;
    }
}
int main(){
    clock_t start,end;
    Rational *array[MAN_TIMES];
    Rational::newMemPool();

    start = clock();
    for(int j = 0;j < 500;j++){
        for(int i = 0;i < MAN_TIMES;i++){
            array[i] = new Rational(i);
        }
        for(int j = 0;j < MAN_TIMES;j++){
            delete array[j];
        }
    }

    end = clock();

    cout<<"Run time:"<<(double)(end -  start)/CLOCKS_PER_SEC * 1000<<"ms"<<endl;

    Rational::deleteMemPool();

    return 0;
}

语法 C++ 编译器 debug

rushour 10 years, 2 months ago

楼主,打打基础吧。。。我都写了好几年c++了。基础好了,性能自然就上去了。不要连基础就没明白就钻研性能问题。

本人是潜水员 answered 10 years, 2 months ago

这种情况用 static_cast 显然是不对的, 你改用 reinterpret_cast 试试呢?

上帝的兔子 answered 10 years, 2 months ago

Your Answer