是否赋值代码会导致崩溃
Does the assignment code will lead to crash?
class SMTkrSym {
enum { SMTKRLEN = 16 };
uint8 data[SMTKRLEN];
public:
SMTkrSym() { memset(&data, 0, sizeof data); }
SMTkrSym(const char* pIn) { if (Read(pIn) < 0) memset(&data, 0, sizeof data); }
int16 Show(char* outstr) const; // display ticker symbol
int16 Read(const char* instr); // read ticker symbol
bool operator==(const SMTkrSym& rhs) const { return strncmp((char*)data, (char*)rhs.data, SMTKRLEN) == 0; }
bool operator!=(const SMTkrSym& rhs) const { return !(*this == rhs); }
bool operator>(const SMTkrSym& rhs) const { return (strncmp((char*)data, (char*)rhs.data, SMTKRLEN) > 0); }
bool operator<=(const SMTkrSym& rhs) const { return !(*this > rhs); }
bool operator<(const SMTkrSym& rhs) const { return (strncmp((char*)data, (char*)rhs.data, SMTKRLEN) < 0); }
bool operator>=(const SMTkrSym& rhs) const { return !(*this < rhs); }
};
unsigned int SMTkrSym::Read(const char* instr)
{
unsigned int i,j;
for (i = 0; (i < SMTKRLEN) && *instr; i++) // display until null
data[i] = *instr++;
for (j = i; j < SMTKRLEN; j++)
data[j] = ' '; // null out rest of symbol
return i; // return actual number of characters
}
这个类的用法如下:
char pData[] = "helloworldyyyyyy";
char* p = pData;
SMTkrSym key1(p);
SMTkrSym key2;
key2 = key1;
pData的长度等于16。
SMTkrSym复制构造函数将调用read函数,并且当instr的长度大于或等于16时,它不会放置' '结束符。
我的问题是当程序运行key2 = key1,它会导致崩溃吗?
当运行key2 = key1时,它将调用默认赋值操作符函数。
但是key1的数据成员变量不包含结束符。
我担心的是如果默认赋值函数使用strcpy函数
复制数据成员变量,可能导致内存溢出。
我想如果赋值函数看起来像memcpy(&key2, &key1,Sizeof (key1)),它不会崩溃。默认赋值是如何工作的?
默认编译器提供的operator=
不会使用strcpy()
复制data[]
…它将安全地复制数组中的所有字符,就像您所说的通过memcpy
一样,尽管它实际上可能不使用memcpy
。
相关文章:
- 为"adjacent"变量赋值时出现问题
- C++中的赋值发生,尽管右侧出现异常
- 赋值运算符在我制作类模板时使代码崩溃
- 复制赋值构造函数中的aligned_alloc内存块在释放时崩溃
- C++初始化复制构造函数中的列表赋值,并在复制构造函数中崩溃
- 为结构字段赋值时程序崩溃
- C++ 赋值崩溃
- 在 malloc 之后为数组赋值会导致崩溃
- 类成员作为对另一个的引用:赋值运算符中的崩溃
- 赋值运算符在 xcode 4 中崩溃,在MSVS2010中运行良好
- C++程序在为指针的2D数组赋值后崩溃
- memset导致std::string赋值崩溃
- 向量赋值崩溃
- 给数组赋值时崩溃
- 通过不返回引用来防止下标操作符的赋值会导致运行时崩溃
- c++在使用类方法给成员赋值时每次都会崩溃
- visualstudio-当给太多动态分配的数组赋值时程序崩溃-C++
- 是否赋值代码会导致崩溃
- 将一个glm::vec3常量引用赋值给另一个glm::vec3时奇怪的崩溃
- 自定义复制赋值操作符使程序崩溃(c++)