#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
using namespace std;
class Teacher
{
private:
static int constructor_count_null;
static int constructor_count_two;
static int constructor_count_copy;
static int constructor_count_valuation;
static int destructor_count;
char* m_name;
int m_age;
public:
Teacher()
{
m_name = nullptr;
m_age = 0;
cout << "调用默认构造函数 " << ++constructor_count_null << "次" << endl;
}
Teacher(char*name,int age)
{
m_name = new char[strlen(name)];
strcpy(m_name, name);
m_age = age;
cout << "调用有参构造函数 " << ++constructor_count_two << "次" << endl;
}
//析构函数
~Teacher()
{
delete []m_name;
cout << "调用析构函数 " << ++destructor_count << "次" << endl;
}
//拷贝构造函数
Teacher(const Teacher& t)
{
this->m_age = t.m_age;
this->m_name = new char[strlen(t.m_name)];
cout << &m_name << endl;
strcpy(m_name, t.m_name);
cout << "调用拷贝构造函数 " << ++constructor_count_copy << "次" << endl;
}
//重载赋值号
Teacher& operator =(const Teacher&t)
{
//首先检测是不是重复赋值
if(this!=&t)
{
//然后将原来的值delete
if(this->m_name!=nullptr)
{
delete[]m_name;
m_name = nullptr;
}
this->m_age = t.m_age;
this->m_name = new char[strlen(t.m_name)];
strcpy(m_name, t.m_name);
cout << "使用重载过的赋值号 " << ++constructor_count_valuation << "次" << endl;
}
return *this;
}
};
int Teacher::constructor_count_copy = 0;
int Teacher::constructor_count_null = 0;
int Teacher::constructor_count_two = 0;
int Teacher::constructor_count_valuation = 0;
int Teacher::destructor_count = 0;
//这个函数我想传入一个类
void func(Teacher t)
{
}
int main( _In_ int argc, _In_reads_(argc) _Pre_z_ char** argv, _In_z_ char** envp )
{
Teacher s("sss", 22);
func(s);
system("pause");
return 0;
}
在debug模式下,会在func退出时出现bug,而在release中不会出现。
我的问题是:
为什么我明明做了深拷贝,debug模式下函数退出,析构匿名对象时会出错?