故事是这样的:有一个固定类型的内存池Pool
,用于存储某些类型T
的元素。在使用alloc()
函数构造并向池中添加新元素时遇到了标题中列出的两个问题:
template <class T, size_t qty, class Alloc = allocator<T>>
class Pool {
array <T*, qty> cells; // Pointers to pre-allocated memory
...
public:
T& alloc (...) { // [2] It is unknown what parameters T's constructor may take
T&& tmp (...); // [2] But I need them to be passed as they are
size_t cellNo = findEmptyCell(); // Returns the number of the cell
*cells[cellNo] = tmp; // Placing the new object into the pool
// [1] "invalid conversion from 'int&& (*)(...)' to 'int'" when T is int
isEmpty[cellNo] = false; // Marking the cell as occupied
return *cells[cellNo];
}
}
因此,1)在这种情况下如何避免不必要的对象复制?
2)有没有一种方法可以将任意参数传递给构造函数?
最佳答案
您正在寻找具有可变参数功能模板的“完美转发”:
template <class... Args>
T& alloc(Args&&... args) {
size_t cellNo = findEmptyCell();
*cells[cellNo] = T(std::forward<Args>(args)...);
isEmpty[cellNo] = false;
return *cells[cellNo];
}
这将采用任意数量的参数,并将它们(将副本复制为左值,移动为右值)到
T
构造函数中。然后,该临时对象将被移动分配到*cells[cellNo]
中。