placement new memory

I am trying to reserve chunks of memory to save records of a struc type. I seem to have the int field down? But, there is one member that is char and I have no idea how to create it and initialize it. Could someone help me write these lines of code. There are two types of memory allocated: placement new and new.

Thanks, B.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Chapter 9 Exercise 3 - Placement new example
#include<iostream>
#include<new>

struct chaff
{
	char dross[20];
	int slag;
};

char buffer1[50];
char buffer2[500];
const int BUF = 512;
const int I = 2;
char buffer[BUF];

int main()
{
	int* slag[2];
		
	slag[0] = new int;

	slag[1] = new (buffer2) int;

	//p3 = new int[I];
	//p4 = new (buffer) int[I];
	int i;
	for (i = 0;  i < I; i++)
		*slag[i] = 1200 + 10 * i;
	
	std::cout << "Memory addresses:\n" << "   heap: " << slag[0] << "   static " << (void *) buffer <<std::endl;
	std::cout << "Memory contents:\n";
	for (i = 0; i < I; i++)
	{
		std::cout << *slag[i] << " at " << &slag[i] << "; ";
	}

	delete [] slag[0];
	std::cout << "Delete memory modules";
	std::cin >> i;


	return 0;
}  
If you can do int why can you not do char? What is different about them to you?
I don't know how to define dross because it has a subscript. slag was easy: int* slag[2];. Plus, I have to initialize it with a string.

B.
new (your_buffer) char[20];??

Also, generally you do not allocate each member of a struct separately - instead it is more typical (and more correct) to allocate the entire struct in one go.

new (your_buffer) chaff;
Last edited on
I tried each construct and can't get either one to initialize. I get pre-compile syntax errors.

B.
Pre-compile syntax errors? You mean preprocessor errors? o_o
I get errors in MS Visual Studio. It flags syntax errors by using red underlines of code that is in error. Then, when you mouse over the error it pops up a error message.

B.
This program works for me
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <new>

struct Example_Class
{
    char c_style_array[20];
    int number;
    std::string normal_string;
    Example_Class()
    : number(7)
    , normal_string("Hello, placement new!")
    {
    }
};

int main()
{
    unsigned char my_buffer[sizeof(Example_Class)];
    Example_Class *p = new (my_buffer) Example_Class;
    std::cout << p->number << std::endl;
    std::cout << p->normal_string << std::endl;
    p->~Example_Class();
}
http://ideone.com/A6B0OG
Topic archived. No new replies allowed.