How many space should be reserved for dynamic class with placement new

with placement new, it turned out that sizeof operator can't tell me the real space needed to set an array (buffer) to hold two successive class object.

i set a class, whose size is 28(sizeof told me), so i set a int *buf = new int[14];//for 14*4 = 56 to give just adequate space for 2 object. but while run time, error occurs. and i have to give a lot of additional space.

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
#include <iostream>
#include <string>
#include <new>

class goodday
{
	std::string a;
public:
	goodday(){ a = "hello"; }
	const std::string & val()const{ return a; }
	~goodday(){}
};

int main()
{
	std::cout << sizeof(goodday);
	int *holder = new int[14];
	goodday *pa = new (holder)goodday;
	goodday *pb = new (holder + sizeof(goodday))goodday;
	std::cout << pa->val() << pb->val();
	pb->~goodday();
	pa->~goodday();
	delete[] holder;
	std::cin.get();
}


but what interesting is that while i give char *holder = new char[56];//56*1=56 it works, no error occurs.

why?
int *holder = new int[14];


Note that arrays are static pointers so basically holder is a pointer to a "static pointer."

Aceix.
why?
the problem is the pointer arithmetic

holder + sizeof(goodday) is the same as &holder[sizeof(goodday)]

in other words: the pointer is incremented by sizeof(goodday) * sizeof(int)
Topic archived. No new replies allowed.