Created
October 14, 2019 18:11
-
-
Save oliverlee/789f40ec6342b0b25a48775c358efa26 to your computer and use it in GitHub Desktop.
placement new
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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