与类共享指针

shared pointers with classes

本文关键字:指针 共享      更新时间:2023-10-16

看到示例代码后我很惊讶。因为当我说自己的时候,我最终明白了聪明的指针在做什么。但似乎还没有。我真的不明白输出如何显示2014.据我所知,就目前看来,这些班级是分开的。因此,除了继承、多态、嵌套分类等之外,它们之间不可能有关系。在学习智能指针时,我可能会跳过一些要点。有人可以照亮学生吗?

#include <iostream>
#include <memory>
class classA
{
    std::shared_ptr<int> ptA;
public:
    classA(std::shared_ptr<int> p) : ptA(p) {}
    void setValue(int n) {
        *ptA = n;
    }
};
class classB
{
    std::shared_ptr<int> ptB;
public:
    classB(std::shared_ptr<int> p) : ptB(p) {}
    int getValue() const {
        return *ptB;
    }
};
int main()
{
    std::shared_ptr<int> pTemp(new int(2013));
    classA a(pTemp);
    classB b(pTemp);
    a.setValue(2014);
    std::cout << "b.getValue() = " << b.getValue() << std::endl;

}

原始指针输出2013法典:

#include <iostream>
#include <memory>
class classA
{
    int* ptA;
public:
    classA(int * p) {
        ptA = new int(*p);
    }
    void setValue(int n) {
        *ptA = n;
    }
    ~classA() {
        delete ptA;
    }
};
class classB
{
    int* ptB;
public:
    classB(int *p) : ptB(p) {}
    int getValue() const {
        return *ptB;
    }
};
int main()
{
    int* pTemp(new int(2013));
    classA a(pTemp);
    classB b(pTemp);
    a.setValue(2014);
    std::cout << "b.getValue() = " << b.getValue() << std::endl;

}

发生的情况是,每个std::shared_ptr对象都有自己的指针(即它有一个作为指针的成员变量),但所有这些指针都指向同一个地方。

让我们使用普通的"原始"指针举一个例子:

int* p = new int(2013);

现在,您有一个指针p指向某个内存。如果我们这样做

int* p2 = p;

然后我们有两个指针,但都指向完全相同的内存

这类似于shared_ptr的工作方式,每个shared_ptr对象都有一个内部指针(成员变量),并且每次复制shared_ptr时(例如将其传递给函数时),内部成员变量都使用源对象指针变量初始化(如上例中初始化p2时), 导致指向同一内存的两个对象的成员指针变量。

让我们删除智能指针的东西,因为它似乎只是让你感到困惑。

您的第一个代码是这样的,总而言之:

int v = 2013;
int* p1 = &v;
int* p2 = &v;
*p1++;  // Makes v = 2014, so *p2 = 2014.

您的第二个版本是这样的:

int v1 = 2013;
int v2 = 2013;
int* p1 = &v1;
int* p2 = &v2;
*p1++;  // Makes v1 = 2014, but v2 = 2013