Skip to content

Instantly share code, notes, and snippets.

@rakslice
Created October 2, 2020 20:08
Show Gist options
  • Save rakslice/3dbd4fc89964a37b4da3dd5a4fc93ef1 to your computer and use it in GitHub Desktop.
Save rakslice/3dbd4fc89964a37b4da3dd5a4fc93ef1 to your computer and use it in GitHub Desktop.
Placement `new` example
#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;
}
@rakslice
Copy link
Author

rakslice commented Oct 2, 2020

$ ./Foo
The Foo at 0064FEC0 is constructing
The inline Foo is at 0064FEC0
The buffer is at 0064FEC8
The Foo at 0064FEC8 is constructing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment