我在为指向对象的指针编写复制构造函数时遇到问题。这是我的确切问题
我有一个类 G1,它有一个对象 s1 作为它的私有数据成员。这是一个结构的对象。
该结构由一个vector<pair<int,pointer to another object of a different class>>.
现在,当我为 G1 创建指针时,一切都很好。
当我尝试将此指针复制到同一类的另一个新指针时,它正在制作一个浅拷贝。
因此,当我尝试删除第一个指针时,第二个指针丢失了它的引用。
我的代码是这样的。
template <typename T,typename V>
class G1{
private:
S<typename T> s1;
public:
G1<T,V>(){}
G1<T,V>(const G1<T,V>& g2):s1(g2.s1){}
};
template<typename T>
struct S{
private:
vector<pair<int,B<T>*>> smap;
public:
S<T>(const S& st){
for(vector<pair<int,B<T>*>>::iterator it = st.getMap().begin(); it!= st.getMap().end(); it++){
B<T> bptr = new B<T>(*it->second);
smap.push_back(pair<*(it)->first,bptr>);
}
}
};
//假设存在仅具有值类型且不需要用户定义的复制构造函数的 B 类。
void main(){
G1<string,string>* g1= new G1<string,string>;
//values loaded into g1.
G1<string,string>* g2= g1;
delete g1;
g2.display(); //Code breaks at this point since I am not able to create two pointers pointing different locations.
// I am not able to make a new copy of the smap vector which has pointers and hence the problem.
}
请有任何建议。在进行指针赋值时会调用复制构造函数吗?在 Visual Studio 中调试时,我看不到任何复制构造函数或赋值运算符函数被调用。
需要为其创建深拷贝的类中的指针成员很简单。当在需要为其创建深拷贝的类中使用其对象的其他类中声明指针时,我感到困惑。
有人可以提供一些关于如何在上述情况下进行深层复制的提示吗?