C++,如果类中存在指针形式的成员变量, 默认赋值运算符在析构的过程中,可能会出现删除已经删除的数据(行为),导致程序异常终止。
解决方式:重载赋值运算符,进行深度复制,demo如下:
strng.h
#include<iostream> #ifndef STRNG_H #define STRNG_H class StringBad { public: StringBad(const char *s); StringBad(); ~StringBad(); StringBad &operator=(const StringBad &st); private: char *str; int len; static int num_strings; }; #endif //STRNG_H
Strng.cpp
#include <cstring> #include "strngbad.h" using std::cout; int StringBad::num_strings = 0; StringBad::StringBad(const char *s) { len = std::strlen(s); str = new char[len + 1]; std::strcpy(str, s); num_strings++; std::cout << num_strings << ":\"" << str << "\" object created\n"; } StringBad::StringBad() { len = 4; str = new char[4]; std::strcpy(str, "C++"); num_string++; std::cout << num_strings << ": \"" << str << "\" default object created\n"; } StringBad::~StringBad() { std::cout << "\"" << str << "\" object deleted,"; --num_strings; std::cout << num_string << "left\n"; delete[] str; } StringBad &StringBad::operator=(const StringBad &st) { if(this == &st){ return *this; } delete[] str; len = st.len; str = new char[len + 1]; std::strcpy(str, st.str); return *this; }
main.cpp
#include <iostream> #include "strng.h" using namespace std; int main() { StringBad src("abcde"); StringBad dest; dest = src; return 0; }