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

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

最佳答案

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

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

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

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

关于c++ - 指针成员未在复制构造函数中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56419244/

相关文章:

c# - Visual Studio 2017 中的 Microsoft Rdlc 报表设计器

c++ - 格式化输出以显示在错误列表的消息部分

c++ - 为什么 vector<double> 接受带有整数元素的 initializer_list?

c++ - 体系结构 x86_64 "_SDL_Init"的 undefined symbol

c++ - 调用正确的虚方法

visual-studio-2017 - VS 2017 不允许滚动错误列表

c++ - CHUNKSTATE 和 STAT_CHUNK 未定义

C++ 升级到 VS2017 : error C2668 about ambiguous call

c++ - 如何将 `std::vector` 成员变量 move 到方法的调用者?

c++ - 将结构传递给函数