標籤: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 勿要對類使用