C++拷贝构造函数调用其他构造函数相关技术咨询
Hey there! Let's walk through your Line class code and break down the key details you need to get right—especially since pointer members can be tricky for folks new to C++. First, I'll fill in the incomplete parts of your code and then explain the critical concepts.
Full Working Version of Your Code
#include <iostream> using namespace std; class Line { public: int getLength( void ); Line( int len ); // 普通构造函数 Line( const Line &obj); // 拷贝构造函数 ~Line(); // 析构函数 private: int *ptr; }; // 普通构造函数:分配内存并初始化指针 Line::Line(int len) { cout << "Normal constructor allocating ptr" << endl; ptr = new int(len); // 补全你未写完的内存分配逻辑 } // 拷贝构造函数:重点实现深拷贝 Line::Line(const Line &obj) { cout << "Copy constructor allocating ptr" << endl; // 深拷贝:为新对象分配独立内存,避免共享地址 ptr = new int(*obj.ptr); } // 析构函数:释放指针指向的内存,防止泄漏 Line::~Line() { cout << "Freeing memory!" << endl; delete ptr; } // 获取长度的成员函数 int Line::getLength(void) { return *ptr; } // 测试代码示例 int main() { Line line1(10); Line line2 = line1; // 触发拷贝构造函数 cout << "Length of line1: " << line1.getLength() << endl; cout << "Length of line2: " << line2.getLength() << endl; return 0; }
Critical Concepts to Grasp
Why Custom Copy Constructor is Non-Negotiable
The default copy constructor that C++ provides does a shallow copy—it just copies the pointer's address, not the value it points to. That meansline1andline2would share the same memory location. When one object gets destroyed, it deletes that memory, leaving the other with a dangling pointer (accessing it causes undefined behavior, like crashes or garbage values).The custom copy constructor I wrote does a deep copy: it allocates new memory for the new object's
ptrand copies the actual value from the original. This keeps each object's memory independent.Destructor's Job
You mustdelete ptrin the destructor to free the memory you allocated withnew. Skip this, and you'll have a memory leak—memory that's reserved but never returned to the system.Common Pitfalls to Avoid
- Forgetting the copy constructor with pointer members: guarantees shallow copy bugs.
- Mismatching
deleteandnew[]: since you allocated a singleint(not an array), usedelete, notdelete[]—mixing these causes undefined behavior. - Skipping self-check in copy assignment (if you add it later): when writing a copy assignment operator, always check
if (this != &obj)to avoid deleting your own memory before copying.
Bonus: Rule of Three
In C++03, when you define one of a destructor, copy constructor, or copy assignment operator, you should define all three (this is the Rule of Three). Your code has the first two, so here's the copy assignment operator to complete the set:
Line& operator=(const Line &obj) { cout << "Copy assignment operator called" << endl; if (this != &obj) { // 防止自赋值 delete ptr; // 释放当前对象的旧内存 ptr = new int(*obj.ptr); // 分配新内存并拷贝值 } return *this; }
内容的提问来源于stack exchange,提问作者Yura

