Created
October 2, 2020 20:08
-
-
Save rakslice/3dbd4fc89964a37b4da3dd5a4fc93ef1 to your computer and use it in GitHub Desktop.
Placement `new` example
This file contains 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 <stdio.h> | |
#include <new> | |
class Foo { | |
int i; | |
int j; | |
public: | |
Foo() { | |
printf("The Foo at %p is constructing\n", this); | |
i = 1; | |
j = 5; | |
} | |
}; | |
class Bar { | |
Foo a; | |
char buf[sizeof(Foo)]; | |
Foo * bufFoo() { | |
return (Foo *) buf; | |
} | |
public: | |
Bar(); | |
}; | |
Bar::Bar() | |
{ | |
printf("The inline Foo is at %p\n", &a); | |
printf("The buffer is at %p\n", buf); | |
new (bufFoo()) Foo(); | |
} | |
int main() { | |
Bar bar; | |
return 0; | |
} |
Author
rakslice
commented
Oct 2, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment