与类共享指针
shared pointers with classes
看到示例代码后我很惊讶。因为当我说自己的时候,我最终明白了聪明的指针在做什么。但似乎还没有。我真的不明白输出如何显示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
相关文章:
- 如何从具有移动语义的类对象中生成共享指针
- 使用共享指针的函数调用,其对象应为 const
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- 如何访问由共享指针保存的类方法?
- 从矢量或地图中删除共享指针
- 使用共享指针时,从共享指针本身释放内存的机制是什么
- 使用共享指针实现复制 c'tor?
- C++/QT:使用指向私有成员的常量指针作为只读数据共享
- 共享指针继承,而不先显式强制转换
- 如何检查类中共享指针的有效性?
- 共享 C++ 的数据成员指针
- std::排序在共享指针的向量上
- 将相同共享指针的副本存储在不同的向量中是否是一种好的做法?
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- 嵌套类、继承和C++中的共享指针
- <Base> <Derived> 具有相同原始指针共享引用的 shared_ptr 和 shared_ptr 实例是否计数?
- 重载流<<运算符,用于指针/共享指针和其他类型的
- RAW指针共享_ptr
- 指针共享习语
- 将memmove函数与临时指针共享相同的地址