Commit 7e10c6d35a813cfe2292f143180664b3096826c7

Authored by Grzegorz Jabłoński
1 parent f39aa06c

Added placement new comment and new version

examples11/02-new/makefile
1 -all: newhandler placementnew placement2 placement3 1 +all: newhandler placementnew placement2 placementnew2
2 2
3 newhandler: newhandler.o 3 newhandler: newhandler.o
4 g++ -g -Wall -pedantic $^ -o $@ 4 g++ -g -Wall -pedantic $^ -o $@
@@ -12,6 +12,12 @@ placementnew: placementnew.o @@ -12,6 +12,12 @@ placementnew: placementnew.o
12 placemenetnew.o: placementnew.cpp 12 placemenetnew.o: placementnew.cpp
13 g++ -g -c -Wall -pedantic $< -o $@ 13 g++ -g -c -Wall -pedantic $< -o $@
14 14
  15 +placementnew2: placementnew2.o
  16 + g++ -g -Wall -pedantic $^ -o $@
  17 +
  18 +placemenetnew2.o: placementnew2.cpp
  19 + g++ -g -c -Wall -pedantic $< -o $@
  20 +
15 placement2: placement2.o 21 placement2: placement2.o
16 g++ -g -Wall -pedantic $^ -o $@ 22 g++ -g -Wall -pedantic $^ -o $@
17 23
@@ -21,4 +27,4 @@ placement2.o: placement2.cpp @@ -21,4 +27,4 @@ placement2.o: placement2.cpp
21 .PHONY: clean 27 .PHONY: clean
22 28
23 clean: 29 clean:
24 - -rm newhandler.o newhandler placementnew.o placementnew placement2.o placement2  
25 \ No newline at end of file 30 \ No newline at end of file
  31 + -rm newhandler.o newhandler placementnew.o placementnew placement2.o placement2 placementnew2.o placementnew2
26 \ No newline at end of file 32 \ No newline at end of file
examples11/02-new/placementnew.cpp
@@ -8,6 +8,7 @@ main () @@ -8,6 +8,7 @@ main ()
8 { 8 {
9 char buf[sizeof (string)]; 9 char buf[sizeof (string)];
10 string *s = new (buf) string; // construct an string at .buf;. invokes: operator new(sizeof(string),buf); 10 string *s = new (buf) string; // construct an string at .buf;. invokes: operator new(sizeof(string),buf);
  11 + // actually undefined behaviour - alignment restrictions might not be fulfilled
11 *s = "hello"; 12 *s = "hello";
12 cout << *s << endl; 13 cout << *s << endl;
13 s->~string(); 14 s->~string();
examples11/02-new/placementnew2.cpp 0 → 100644
  1 +#include <new>
  2 +#include <string>
  3 +#include <iostream>
  4 +using namespace std;
  5 +
  6 +int
  7 +main ()
  8 +{
  9 + std::aligned_storage_t<sizeof(string), alignof(string)> buf;
  10 + string *s = new (&buf) string; // construct an string at .buf;. invokes: operator new(sizeof(string),buf);
  11 + // actually undefined behaviour - alignment restrictions might not be fulfilled
  12 + *s = "hello";
  13 + cout << *s << endl;
  14 + s->~string();
  15 +};