C++ 中memset 勿要對類使用

來源:互聯網
上載者:User

標籤:unsigned   strong   rust   emc   target   等於   texture   material   超過   

C++ 中memset 勿要對類使用

 

參考連結: 
http://www.cppblog.com/qinqing1984/archive/2009/08/07/92479.html

百度百科第一次這麼給力: 
void *memset(void *s, int ch, size_t n); 
函數解釋:將s中前n個位元組 (typedef unsigned int size_t )用 ch 替換並返回 s 。 
memset:作用是在一段記憶體塊中填充某個給定的值,它是對較大的結構體或數組進行清零操作的一種最快方法。

memset() 函數常用於記憶體空間初始化: 

 char str[100]; memset(str,0,100);

用來對一段記憶體空間全部設定為某個字元,一般用在對定義的字串進行初始化為‘

memset(a, ‘\0‘, sizeof(a));

memcpy用來做記憶體拷貝,你可以拿它拷貝任何資料類型的對象,可以指定拷貝的資料長度:  

char a[100], b[50];memcpy(b, a, sizeof(b)); //注意如用sizeof(a),會造成b的記憶體位址溢出。

strcpy就只能拷貝字串了,它遇到’\0’就結束拷貝: 

char a[100], b[50];strcpy(a,b);

如用strcpy(b,a),要注意a中的字串長度(第一個‘\0’之前)是否超過50位,如超過,則會造成b的記憶體位址溢出。 
  

下面開始:

class Material{public:    Material(){ setDefaults();}    void setDefaults(){ memset(this,0,sizeof(*this));}    int mark;    char materialName[256]; // material name    Vector3 ambient;    // ambient    Vector3 diffuse;    // diffuse    Vector3 specular;   // specular    int shininess;  //    float alpha;    //    bool isSpecular;char textureName[256];  // texture namechar textureTransName[256]; // transparent texture name};

這段代碼完美無瑕。再看看下面的:

class Material{public:    Material(){ setDefaults();}    void setDefaults(){ memset(this,0,sizeof(*this));}    int mark;    std::string materialName;   // material name    Vector3 ambient;    // ambient    Vector3 diffuse;    // diffuse    Vector3 specular;   // specular    int shininess;  //    float alpha;    //    bool isSpecular;std::string textureName;    // texture namestd::string textureTransName;   // transparent texture name};

上面的代碼會造成記憶體泄露: 
所以對於C++的std::string來說,要使用C++風格的初始化。

在網上看到這樣一條評論,覺得有道理: 
任何類都不能用memset, 一旦暴力,就等於你強姦了她的內部資料,她已經崩潰了

 

C++ 中memset 勿要對類使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.