gpt4 book ai didi

C++11 就地构造混淆

转载 作者:行者123 更新时间:2023-11-30 05:48:55 27 4
gpt4 key购买 nike

我正在尝试使用 vector 作为自定义存储容器的一部分。我想在将对象添加到容器时避免任何临时对象,并且我想手动构造对象来代替以前释放的对象。如何在不创建临时对象的情况下执行此操作?

代码:

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;
}

最佳答案

你可以这样做:

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...);
}
}

关于C++11 就地构造混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28005238/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com