简体   繁体   中英

Call constructor using args in another function using placement new

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

您对Push()调用应该只是Push(5, 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM