[英]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: " << © << " -> 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值以編寫新的值。 在這種情況下,實現復制構造函數的正確方法是什么?
復制構造函數是構造函數,而不是賦值運算符。 差異恰恰在於缺乏現有的破壞資源。 您無需銷毀任何東西,只需初始化即可。
之所以調用復制構造函數是因為您沒有使它接受const引用:
TestClassA& operator=(const TestClassA& tmp)
// ^ ^
在示例中初始化的是tmp
參數,而不是運算符的this
。 當然,您將需要一個局部變量來使swap
技巧起作用,但至少在代碼中它是顯式的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.