環境:linux(win7下vs不會出現崩潰)
我喜歡先說結果,運行崩潰在 C1.m_Content = "aaaa":
struct ChatMsg { int m_nTargetGuid; std::string m_Content; ChatMsg() { memset(this, 0, sizeof(*this)); } }; int main() { ChatMsg C1; C1.m_Content = "aaaa"; return 0; }
原因分析:
首先需要了解String類內部構造,內部也是很復雜,有很多指針,當memset時都為0了,破壞了內部結構,使得內部指針都為0,調用賦值構造函數時會出啥亂子就不清楚了
具體想了解內部結構的參考帖子:https://www.cnblogs.com/findumars/p/5006181.html
總結:
memset不可初始化string類,當然最好不要初始化模板類,擁有虛函數表的類等等