I have a class that isn't allowed to have a copy constructor for various reasons (one is because the struct has a pointer to an array that I don't want to delete several times nor do I want to copy/clone it).
I'd like to construct the object in a push function. Like to push onto an array. I have the following test code but I can't seem to call it using a construct (unless its a copy constructor which I explicitly don't want).
To be clear the object shouldn't be constructed until it's ready to be in the array which is why I'm using placement new
#include<utility>
#include<cstdlib>
#include<new>
struct Test{
int a, b, *p;
Test(int a, int b) : a(a), b(b), p(nullptr) { }
Test(const Test&) = delete;
};
Test*ptest;
int offset;
template<typename... Args>
void Push(Args&&... args) {
new (&ptest[offset++]) Test(std::forward<Args>(args)...);
}
int main(){
ptest = (Test*)malloc(sizeof(Test)*10); //Array of 10
Push(Test{5, 1});
}
Your call to Push()
should only be Push(5, 1)
instead.