在C++中,byte数组更常见的写法是使用char数组,那么在拷贝构造函数中涉及byte数组时,需要注意可能存在指针复制的问题。这也是出现“Suspicious assignment in copy constructor”的原因。解决这一问题的方法有以下几种:
class MyClass { public: MyClass(const MyClass& other) // 拷贝构造函数 { // 进行深拷贝 size = other.size; data = new byte[size]; memcpy(data, other.data, size); } private: byte* data; int size; };
class MyClass { public: MyClass(const MyClass& other) // 拷贝构造函数 { size = other.size; data = new byte[size]; memmove(data, other.data, size); } private: byte* data; int size; };
class MyClass { private: MyClass(const MyClass& other); };