[問題] reinterpret_cast 使用時機

看板C_and_CPP作者 (C++1X)時間14年前 (2010/01/05 18:34), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串1/1
在網路上看到有人在問 shallow copy問題時 他的程式碼大概如下 class C { public: C* shallow_clone() { C* p = reinterpret_cast<C>(new char[sizeof(C)]); . . . return p; } }; 後來有人建議他的程式改成 class C { public: C* shallow_clone() { // C* p = reinterpret_cast<C>(new char[sizeof(C)]); // Avoidable undefined behavior: instance of C exists in a potentially // not remotely valid state. char* p = new char[sizeof(C)]; . . . // return p; return reinterpret_cast<C*>(p); } }; 我想請問為什麼 reinterpret_cast要改到後面? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.137.16.60

01/05 18:44, , 1F
應該沒一定要 只是reinterpret_cast<這裡要C*>
01/05 18:44, 1F

01/05 18:52, , 2F
話說這種方法很危險...要考慮到細節像是vptr之類的..
01/05 18:52, 2F

01/05 18:53, , 3F
我覺得用一個private/protected的ctor比較好...
01/05 18:53, 3F

01/05 23:14, , 4F
C* p = reinterpret_cast<C>(new char[sizeof(C)]); Typo?
01/05 23:14, 4F

01/05 23:17, , 5F
看到一樓的推文了   XD
01/05 23:17, 5F
文章代碼(AID): #1BGnMkp2 (C_and_CPP)