首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11结构就地混淆

C++11结构就地混淆
EN

Stack Overflow用户
提问于 2015-01-18 06:55:41
回答 1查看 478关注 0票数 1

我正在尝试使用一个向量作为自定义存储容器的一部分。在将对象添加到容器中时,我希望避免任何临时操作,并且我希望手动构造对象,而不是以前释放的对象。如何才能在不创建临时文件的情况下做到这一点?

代码:

代码语言:javascript
复制
struct Mesh
{
    float data;

    Mesh(float a) : data(a)
    {
    }
};


template<typename T>
class IDStorage
{
public:
    template <typename... Arguments>
    void AddItem(Arguments&&... args)
    {
        if (!mFreeIndices.empty())
        {
            const uint32_t freeIndex = mFreeIndices.back();
            mFreeIndices.pop_back();

            // mItems[freeIndex] = Item(0, 1, args...);     NOPE - I want to avoid this temporary!
            // mItems[freeIndex].Item(0, 1, args...);   NOPE
            // new (&mItems[freeIndex]) Item(0, 1, args...);     NOPE
            // How can I avoid a temporary in this case?
        }
        else
            mItems.emplace_back(0, 1, args...);
    }

    void FreeItem(uint32_t index)
    {
        mFreeIndices.push_back(index);
        // ignore destructor
    }


private:
    struct Item {
        uint32_t mIndex;
        uint32_t mVersion;
        T mItem;

        template <typename... Arguments>
        Item(uint32_t index, uint32_t version, Arguments&&... args) : mIndex(index), mVersion(version), mItem(args...)
        {
        }
    };

    std::vector<Item> mItems;
    std::vector<uint32_t> mFreeIndices;
};

int _tmain(int argc, _TCHAR* argv[])
{
    IDStorage<Mesh> meshStorage;
    meshStorage.AddItem(1.0f);
    meshStorage.FreeItem(0);
    meshStorage.AddItem(2.0f);

    return 0;
}
EN

回答 1

Stack Overflow用户

发布于 2015-01-18 09:38:56

你可以这样做:

代码语言:javascript
复制
template <typename... Arguments>
void AddItem(Arguments &&... args)
{       
    if (!mFreeIndices.empty())
    {
        const uint32_t freeIndex = mFreeIndices.back();
        mFreeIndices.pop_back();

        // this doesn't create a temporary          
        //mItems[freeIndex].mIndex = 0;
        //mItems[freeIndex].mVersion = 1;
        mItems[freeIndex].mItem = T(args...);
    }
    else
    {
        mItems.emplace_back(0, 1, args...);
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28005238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档