我正在尝试实现引用计数。对象的每个拷贝都应该增加它的计数器。 我的代码看起来
class Person{
public:
struct Kids{
Kids(){
count = 2;
boy = "Alex";
girl= " Lisa";
}
int count;
string boy;
string girl;
};
Person( string name , int age){
this -> name = name;
this -> age = age;
}
Person( const Person& a){
one = a.one;
one -> count++;
age = a.age;
name = a.name;
for( int i = 0; i < 5; i++){
family[i] = a.family[i];
}
};
void PrintIt(){
cout << one -> count << endl;
}
private:
Kids *one;
string name;
int age;
Kids family[5];
};
int main(){
Person one("Jogn",50);
//return 0;
Person two(one);
two.PrintIt();
}
它会抛出段错误。我试图将对象作为指针传递给复制构造函数,这导致了相同的输出。如何创建一个复制构造函数,它将通过指针指向对象,这将导致可能的引用计数?
最佳答案
您是否尝试过 std::shared_ptr
,它在 C++ 11 中可用。该模板类具有经过良好测试和开发的优点。这里有一个 link到文档。
关于c++ - 带引用计数的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36796468/