不要随意用memset对C++复杂对象进行数据清除

//#include <cstring>        
void* memset( void* dest, int ch, std::size_t count );

它会 转换值 ch 为 unsigned char 并复制它到 dest 所指向对象的首 count 个字节。
因此memset方法会破坏对象内部保持状态的私有变量,从而造成未知后果。

示例

下例对std::string对象a进行了
memset操作,结果再次给对象a赋值时, a的值明显出现了异常。

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string a = "Test";
    cout << a << endl;          // Test

    memset(&a, 0, sizeof(a));   // 破坏了C++对象的内部组织
    a = "Test2";
    cout << a << endl;          // p觍_{ 
    
    return 0;
}

分类:

技术点:

相关文章: