gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 22:34:37 25 4
gpt4 key购买 nike

在我的申请中

#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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com