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

时间:2019-06-02 22:00:09

标签: c++ visual-studio-2017

在我的应用程序中

#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 值来编写新的值。在这种情况下,实现复制构造函数的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

复制构造函数是构造函数,而不是赋值运算符。差异恰恰在于缺乏现有的破坏资源。您无需销毁任何东西,只需初始化即可。

之所以调用复制构造函数是因为您没有使它接受const引用:

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

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

相关问题