Copy constructors, assignment operators, and exception safe assignment

Copy constructors, assignment operators, and exception safe assignment

link: http://www.cplusplus.com/articles/y8hv0pDG/

// copy constructor
Myclass::Myclass(const Myclass& myclass)
{
    printf("this is my class copy\n");
    
    if(this->m_arry)
    {
        printf("42\n");
        delete[] this->m_arry;
    }
    else
        printf("41\n");
    
    
    m_num = myclass.m_num;
    m_arry = new int[m_num];
    
    for(int i = 0; i < m_num; i++)
    {
        printf("40\n");
        m_arry[i] = myclass.m_arry[i];
    }
}

Error: 这是我犯的第一错误: 这是一个构造函数, 而我在一开始还没复制之前就已经delete 这属于delete一个无效的指针。构造函数只是对申请的内存 进行初始化。而不是assignment function.

Overview of C++ Variable Initialization

https://greek0.net/cpp/initialization.html

猜你喜欢

转载自www.cnblogs.com/yetanghanCpp/p/9050080.html