Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::shared_ptr operator=更改对象,而不是指针值?_C++ - Fatal编程技术网

C++ std::shared_ptr operator=更改对象,而不是指针值?

C++ std::shared_ptr operator=更改对象,而不是指针值?,c++,C++,在下面的小程序中,我希望能够通过更改s的值来更改M中的值。但显然我做不到。一种可行的方法是更改原始指针,但这并不安全: #include <iostream> #include <memory> class M{ public: std::shared_ptr<int> t; }; std::shared_ptr<int> s; int main() { M m; m.t = s; s = std::make_shared<

在下面的小程序中,我希望能够通过更改
s
的值来更改
M
中的值。但显然我做不到。一种可行的方法是更改原始指针,但这并不安全:

#include <iostream>
#include <memory>
class M{
  public:
  std::shared_ptr<int> t;
};
std::shared_ptr<int> s;
int main() {
  M m;
  m.t = s;
  s = std::make_shared<int>(5);
  std::cout << m.t << std::endl; //prints 0
}
#包括
#包括
M类{
公众:
std::共享的ptr t;
};
std::共享的ptr;
int main(){
M M;
m、 t=s;
s=标准::使_共享(5);

std::cout共享指针的整个功能是安全地传递指针,就像它只是一个原始指针一样。这意味着
m.t=s
只需复制
s
当前正在管理的指针,并将其存储在
t
中。然后它更新其内部引用计数,以便如果
s
t
超出范围,指针将不会被删除。如果您随后更改
s
指向的内容,则它不应更改
t
,因为
t
不知道
s
。如果您希望更改
s
的内容也会影响
m.t
,则必须更改
s
的内容。请尝试
*s=5;std::您是否可以交换订单。首先执行
s=std::make_shared(5);
,然后执行
m.t=s;
。然后您可以执行
*s=6;
*m.t=7;
,这两种操作都会影响其他共享智能指针。