带引用计数的复制构造函数

Copy constructor with reference counting

我正在尝试实现引用计数。对象的每个副本都应该增加它的计数器。 我的代码看起来

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 中可用。这个模板 class 具有经过良好测试和开发的优点。这里有一个 link 文档。

Kids *one;

似乎未初始化。当你向它复制一个值时。这个值也是单元化的,因为它是私有的,我没有看到它的任何初始化代码。您必须添加类似

的内容
kids(new Kids())

在非副本的Person构造函数中。

ps。不要忘记 operator= 和析构函数。

只需在私有和外部创建一个静态变量 class 使用范围解析运算符将其初始化为零。然后在你的构造函数中将它加一。每次创建一个对象时,都会调用其构造函数,并且静态变量会递增 1。然后,您可以在任何需要的地方显示该变量(再次使用范围解析运算符)。