#include <iostream>
class MyBase {
protected:
int _id;
public:
MyBase():_id(0) {}
MyBase( int id ):_id(id) {}
int getId() {return _id; }
};
class MyClass: public MyBase {
public:
MyClass() {}
MyClass( int id ):MyBase( id ) {}
};
int myclass_mem[ sizeof(MyClass)/sizeof(int) ];
using namespace std;
MyBase* test()
{
return new (myclass_mem)MyClass( 100 );// 這裡 (1)
//return new MyClass( 100 ); // (2)
}
int
main( int argc, char* argv[] )
{
int len = sizeof( myclass_mem );
cout << "The size of myclass_mem is " << len << endl;
cout << "content of myclass_mem" << endl;
for( int i=0; i<len; i++ )
cout << myclass_mem[i] << " ";
cout << endl;
MyBase* base = ::test();
cout << base->getId() << endl;
cout << "content of myclass_mem" << endl;
for( int i=0; i<len; i++ )
cout << myclass_mem[i] << " ";
cout << endl;
}
class MyBase {
protected:
int _id;
public:
MyBase():_id(0) {}
MyBase( int id ):_id(id) {}
int getId() {return _id; }
};
class MyClass: public MyBase {
public:
MyClass() {}
MyClass( int id ):MyBase( id ) {}
};
int myclass_mem[ sizeof(MyClass)/sizeof(int) ];
using namespace std;
MyBase* test()
{
return new (myclass_mem)MyClass( 100 );// 這裡 (1)
//return new MyClass( 100 ); // (2)
}
int
main( int argc, char* argv[] )
{
int len = sizeof( myclass_mem );
cout << "The size of myclass_mem is " << len << endl;
cout << "content of myclass_mem" << endl;
for( int i=0; i<len; i++ )
cout << myclass_mem[i] << " ";
cout << endl;
MyBase* base = ::test();
cout << base->getId() << endl;
cout << "content of myclass_mem" << endl;
for( int i=0; i<len; i++ )
cout << myclass_mem[i] << " ";
cout << endl;
}
以執行的結果來說,我實在是分辨不出來 (1) 與 (2) 有甚麼分別。
後來我用 gcc -S 去分別產生組合語言碼,總算是大致猜到了,原來以 (1) 的方法來寫,會把 new 以後的結果也複製到 myclass_mem 這個陣列裡面。
所以加上輸出 myclass_mem 內容的程式碼,再分別產生執行檔來看執行結果就很清楚了。
真是特別。
沒有留言:
張貼留言