I want to do a "delay creator", it will save original object and assign it to a new object which from memory pool in any time(under C++17):
using DelaySpawnFunc = std::function<void(void *)>; // the lambda will capture original object and
// do assignment
class Test final {
public:
template <typename T>
void SaveSpawnInfo(T&& obj) {
DelaySpawnFunc func = [=, c = std::move(obj)](void* elem) { // capture original object
(*((T *)elem)) = std::move(c);
};
spawnFuncs_.push_back(func);
}
// call this function in any time I want
void DoSpawn() {
for (auto& assign: spawnFuncs_) {
void* elem = MemoryPool::Instance().Alloc(); // allocate a piece of memory from pool
assign(elem);
}
}
private:
std::vector<DelaySpawnFunc> spawnFuncs_;
};
It works correctly when I use:
struct NoUniquePtr final {
int a;
};
int main() {
Test test;
test.SaveSpawnInfo<NoUniquePtr>(NoUniquePtr{});
return 0;
}
But with std::unique_ptr
, it can't compile:
struct WithUniquePtr final {
std::unique_ptr<int> a;
};
int main() {
Test test;
test.SaveSpawnInfo<NoUniquePtr>(NoUniquePtr{}); // ERROR: can't compile
return 0;
}
The error say:
mistaken.cpp(11,28): error C2280: “WithUniquePtr &WithUniquePtr::operator =(const WithUniquePtr &)”: attempts to reference a deleted function
mistaken.cpp(34,1): message : The compiler has been generated here “WithUniquePtr::operator =”
mistaken.cpp(34,1): message : “WithUniquePtr &WithUniquePtr::operator =(const WithUniquePtr &)”: Calls a deleted or inaccessible function due to a data member “std::unique_ptr<int,std::default_delete<int>> &std::unique_ptr<int,std::default_delete<int>>::operator =(const std::unique_ptr<int,std::default_delete<int>> &)”,
C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.34.31933\include\memory(3257,17): message : “std::unique_ptr<int,std::default_delete<int>> &std::unique_ptr<int,std::default_delete<int>>::operator =(const std::unique_ptr<int,std::default_delete<int>> &)”: the function has been implicitly removed
Why it call WithUniquePtr::operator=(const WithUniquePtr&)
rather than WithUniquePtr::operator=(WithUniquePtr&&)
? And how can I modify it to compile successful?