类指针数组浅拷贝:如何修正Picture_Pair的拷贝构造函数?
Picture_Pair Class Let's break down what's wrong with your current code and fix it step by step.
1. Name Collision Problem
Your copy constructor parameter is named pp, which clashes with your class's private member array pp. When you write pp = pp.pp, you're actually trying to access the parameter's non-existent pp member instead of the source object's pointer array. We need to rename the parameter to avoid this conflict—other is a standard, readable choice.
2. Array Assignment Limitation
You can't directly assign one array to another using the = operator in C++. For a shallow copy of your pointer array, you need to copy each element individually.
Here's the corrected version of your class with a proper shallow copy constructor:
#ifndef PICTURE_PAIR_H #define PICTURE_PAIR_H class Picture; // Forward declaration class Picture_Pair { private: Picture* pp[2] {nullptr, nullptr}; // Pointers to the two Pictures public: // Shallow copy constructor Picture_Pair(const Picture_Pair& other) { // Copy each pointer individually (shallow copy) pp[0] = other.pp[0]; pp[1] = other.pp[1]; } // Add a default constructor (required since we defined a user-defined copy constructor) Picture_Pair() = default; // Don't forget to declare/destructors if you manage Picture object lifetimes! }; #endif // PICTURE_PAIR_H
What This Does
- The shallow copy constructor takes a
const Picture_Pair& other(the source object we're copying from). - We copy each pointer in
other.ppto our ownpparray. This means both the originalPicture_Pairand the new copy will point to the samePictureobjects—this is exactly the behavior of a shallow copy.
Critical Note
Since this is a shallow copy, watch out for double deletion if your Picture_Pair class is responsible for deleting the Picture objects. If both the original and copied Picture_Pair try to delete the same pointers in their destructors, you'll get undefined behavior. If you ever need a deep copy (where each Picture_Pair owns its own Picture instances), you'd have to allocate new Picture objects and copy their data instead of just copying pointers.
内容的提问来源于stack exchange,提问作者Micka1895

