【问题标题】:templated placement new and destructor模板化放置 new 和析构函数
【发布时间】:2013-02-16 20:41:19
【问题描述】:

为什么不编译?

template <typename T>
class Pool{

    char Buff[sizeof(T)*256];

public:

    Pool(){
        T* item = reinterpret_cast<T*>(&Buff[0]);
        for(int i =0 ; i<256;i++)
            item[i] = new(&item[i]) T();
    }

    ~Pool(){
        T* item = reinterpret_cast<T*>(&Buff[0]);
        for(int i =0 ; i<256;i++)
            item[i] -> ~ T();   
    }

    void reset(unsigned int i){
        T* item = reinterpret_cast<T*>(&Buff[0]);
        item[i]->~T();
        item[i]->T();
    }
}

我显然想要实现的是在原始内存数组上调用placement new(应该调用构造函数ok)。然后我想调用数组中项目的析构函数和构造函数。问题是 Item 是模板,所以如果我使用

Pool<FooBar>

编译器希望找到“FooBar()”和“~FooBar()”而不是“T()”和“~T()”。 有什么特殊的语法可以做到这一点吗?

我使用的是 C++03 而不是 C++11

【问题讨论】:

    标签: c++ templates constructor destructor placement-new


    【解决方案1】:

    您的语法不太正确。以下应该可以解决问题:

    Pool() {
        T* item = reinterpret_cast<T*>(&Buff[0]);
        for(int i = 0; i < 256; i++)
            new(&item[i]) T();
    }
    
    ~Pool() {
        T* item = reinterpret_cast<T*>(&Buff[0]);
        for (int i = 0; i < 256; i++)
            item[i].~T();
    }
    
    void reset(unsigned int i) {
        T* item = reinterpret_cast<T*>(&Buff[0]);
        item[i].~T();
        new(&item[i]) T();
    }
    

    【讨论】:

    • +1 逐字记录我将要发布的内容(除了最后一个new,电话,我有new(item+i) T();
    • 谢谢,似乎 GCC 为 (item+i) 和 (&item[i]) 生成了相同的程序集,谢谢指定,也许 (item+i) 更清晰易读。
    • @DarioOO 嗯。各有各的。有些人更喜欢你拥有它的方式。我一直是一个指针算术的人。
    • @DarioOO:从语义上讲,它们是完全等价的。选择纯粹是风格。
    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-08
    • 1970-01-01
    • 2018-09-08
    • 2011-05-24
    • 2018-04-30
    相关资源
    最近更新 更多