[問題] reinterpret_cast 使用時機
在網路上看到有人在問 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
01/05 18:44, 1F
推
01/05 18:52, , 2F
01/05 18:52, 2F
→
01/05 18:53, , 3F
01/05 18:53, 3F
→
01/05 23:14, , 4F
01/05 23:14, 4F
→
01/05 23:17, , 5F
01/05 23:17, 5F