智能指针本质上是一个对象。把它当成管理一个指针的对象即可。
关键结论:
用于函数参数时(函数内部 reset 持有指针),如果是值传递,函数调用完毕后,是不会更改实参内持有指针的。这符合一般对象的预期。见 test2 与 test4。
#include <cstring>
#include <iostream>
#include <memory>
#include <unordered_set>
int g = 9;
class A{
public:
~A(){
std::cout << "deconstruct of A " << _num << std::endl;
}
void setNum(int n){
_num = n;
}
int getNum(){
return _num;
}
private:
int _num;
};
class MyPtr{
public:
MyPtr(){
_pa = nullptr;
}
MyPtr(A* pa){
_pa = pa;
}
MyPtr(const MyPtr& other){
_pa = other._pa;
}
MyPtr& operator= (const MyPtr& other){
_pa = other._pa;
return *this;
}
void setPA(A* pa){
_pa = pa;
}
A* getPA(){
return _pa;
}
private:
A* _pa;
};
void say(int*& a) { a = &g; }
void ref(std::shared_ptr<A> &p){
std::shared_ptr<A> ts(

本文探讨了C++中智能指针作为函数参数时的行为,特别是值传递的情况。总结关键结论:当智能指针以值传递给函数并进行reset操作后,函数外部的原始智能指针不受影响。
最低0.47元/天 解锁文章

668

被折叠的 条评论
为什么被折叠?



