指针成员未在复制构造函数中初始化

Pointer member is not initialized in copy constructor

在我的申请中

#include <iostream>

class TestClassA
{

public:
    int* m_ptr;
    TestClassA(int a)
    {
        m_ptr = new int(a);
        std::cout << "Constructor. this: " << this << " m_ptr: " << m_ptr << std::endl;
    }

    TestClassA(const TestClassA& copy)
    {
        std::cout << "Copy Constructor. copy: " << &copy << " -> this: " << this << std::endl;
        std::cout << "Copy Constructor. old this->m_ptr: " << m_ptr << std::endl;
        delete m_ptr; // not initialized pointer
        m_ptr = new int;
        std::cout << "Copy Constructor. new this->m_ptr: " << m_ptr << std::endl;
        *m_ptr = *copy.m_ptr;
    }

    // passing by value, thus a copy constructor calls first
    TestClassA& operator=(TestClassA tmp)
    {
        std::cout << "Copy assignment " << this << " <- " << &tmp << std::endl;
        std::swap(m_ptr, tmp.m_ptr);
        return *this;
    }


    ~TestClassA()
    {
        std::cout << "Destructor " << this << std::endl;
        delete m_ptr;
        m_ptr = nullptr;
    }
};

void testAssignment()
{
    TestClassA tca1(1);
    std::cout << "tca1.m_ptr: " << tca1.m_ptr << std::endl;

    TestClassA tca2(2);
    std::cout << "tca2.m_ptr: " << tca2.m_ptr << std::endl;
    tca2 = tca1;
}

int main()
{
    testAssignment();
    return 0;
}

当我调用赋值运算符按值接收参数时,复制构造函数调用。我猜是创建一个临时变量并将tcs1的状态复制到其中。问题是 m_ptr 这个临时成员没有初始化,所以我不能删除以前的 m_ptr 值写一个新的。在这种情况下,实现复制构造函数的正确方法是什么?

复制构造函数是构造函数,不是赋值运算符。区别恰恰在于没有要销毁的现有资源。您不需要销毁任何东西,只需初始化即可。

复制构造函数被调用,因为你没有让它接受常量引用:

TestClassA& operator=(const TestClassA& tmp)
//                    ^               ^

例子中初始化的是tmp参数,不是运算符的this。 当然,您需要一个局部变量才能使 swap 技巧起作用,但至少它会在您的代码中明确显示。