嗨,我一直在练习放置 new 并使用它来创建对象。考虑以下:
class PNewTesting
{
private:
string words;
public:
PNewTesting(const string & w = "Placement new testing");
};
PNewTesting::PNewTesting(const string & w)
{
words = w;
cout << words << " constructed" << endl;
}
int main()
{
char * buffer = new char[BUF];
PNewTesting *p1,*p2;
p1 = new (buffer)PNewTesting;
p2 = new PNewTesting("Placing object in heap");
cout << "Memory addresses: " << endl;
cout << "buffer: " << (void *)buffer << endl;
cout << "object placed in buffer: " << p1 << endl;
cout << "object in heap: " << p2 << endl;
}
这部分让我感到困惑,是当我写作时cout << "buffer: " << &buffer << endl;
,这会给我一个与写作时不同的地址cout << "buffer: " << (void *)buffer << endl;
问题是 和 之间有什么区别&buffer
,(void*)buffer
为什么每个人都给我一个不同的地址。