Skip to content

Instantly share code, notes, and snippets.

@oliverlee
Created October 14, 2019 18:11
Show Gist options
  • Select an option

  • Save oliverlee/789f40ec6342b0b25a48775c358efa26 to your computer and use it in GitHub Desktop.

Select an option

Save oliverlee/789f40ec6342b0b25a48775c358efa26 to your computer and use it in GitHub Desktop.
placement new
#include <iostream>
#include <vector>
struct C {
C(int a, int b) : a_{a}, b_{b} { std::cout << "ctor" << std::endl; }
~C() { std::cout << "dtor" << std::endl; }
int a_;
int b_;
} __attribute__((packed));
int main() {
{
std::cout << "constructing C on the stack" << std::endl;
C{0, 1};
}
std::cout << std::endl;
{
std::cout << "using placement new" << std::endl;
std::vector<uint8_t> v(sizeof(C));
std::cout << "size of v: " << v.size() << std::endl;
new (v.data()) C{2, 3};
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment