放置新的結果總是似乎與我提供給放置新的內存指針相同。隨着GCC這似乎是正確的,即使與虛擬功能,如類...放置 - 新地址vs原始內存地址
#include <iostream>
#include <vector>
using namespace std;
class A
{
public:
int a;
virtual ~A() {}
};
int main()
{
void *mem = malloc(sizeof(A));
A* ptr = new(mem) A();
cout << "sizeof(T) = " << sizeof(A) << endl;
cout << "mem = " << mem << endl;
cout << "ptr = " << ptr << endl;
cout << "addr a = " << &(ptr->a) << endl;
ptr->~A();
free(mem);
return 0;
}
這個程序的輸出是(注:64位Linux)...
sizeof(T) = 16
mem = 0x1a41010
ptr = 0x1a41010
addr a = 0x1a41018
不C++保證mem和ptr是相同的還是僅僅是GCC巧合?在一個更大的可移植程序中,我將不得不保存mem和ptr,還是可以保留其中一個,並在需要時進行投射?
爲了澄清這個問題,我知道內存分配器有時會在指向內存塊之前的單詞中放入分配塊的大小。 C++編譯器是否允許使用這樣的技巧,並說VMT指針在對象指針指向的內存塊之前的單詞中?在這種情況下,mem和ptr會有所不同。
這是一個很好的答案,但它有多權威?它是基於標準還是特定編譯器的實現? – goertzenator 2012-03-11 22:25:54
@goertzenator在C++標準中定義了3個'new'操作符。我建議你是C++程序中最常用的一個。請參閱[這裏](http://cplusplus.com/reference/std/new/operator%20new/)瞭解完整的文檔和使用示例。 – 2012-03-12 17:53:59