Ym影子 2018-01-30 09:18 采纳率: 100%
浏览 1033
已采纳

关于C++ 函数参数为类对象时遇到的bug

 #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模式下函数退出,析构匿名对象时会出错?

  • 写回答

5条回答 默认 最新

  • kongrenxin 2018-01-30 09:35
    关注

    m_name = new char[strlen(name) + 1];
    this->m_name = new char[strlen(t.m_name) + 1];

    改成如上两句就行了
    在字符串分配空间的时候,需要多给一个字节,用来存放\0字符(因为strlen计算的长度是不包含\0的)。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备
  • ¥20 delta降尺度方法,未来数据怎么降尺度
  • ¥15 c# 使用NPOI快速将datatable数据导入excel中指定sheet,要求快速高效
  • ¥15 再不同版本的系统上,TCP传输速度不一致
  • ¥15 高德地图2.0 版本点聚合中Marker的位置无法实时更新,如何解决呢?
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题