故事是这样的:有一个固定类型的内存池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];
}
这将接受任意数量的参数,并将它们(左值复制,右值 move )转发到 T
构造函数中。然后,该临时对象将被 move 分配到 *cells[cellNo]
中。
关于c++ - move 语义 : invalid conversion from `type&&` to `type` . 模板:将未知参数传递给重载函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35559323/