[英]Returning a smart pointer and assign it a value doesn't work
I am having some problems modifying the content of a smart pointer returned by a class function. 我在修改类函数返回的智能指针的内容时遇到一些问题。 Returning a reference to the pointer would be a solution, but I am concerned of it as a bad practice.
返回对指针的引用将是一个解决方案,但我担心它是一种不良做法。
This is my code: 这是我的代码:
#include <memory>
#include <iostream>
class Foo
{
public:
Foo() : ptr_(new int(5)) {};
~Foo() {};
std::shared_ptr<int> bar()
{
return ptr_;
}
void print()
{
std::cout << *ptr_ << std::endl;
}
private:
std::shared_ptr<int> ptr_;
};
int main()
{
Foo f;
f.print();
// First case
f.bar() = std::make_shared<int>(23);
f.print();
// Second case
f.bar().reset(new int(23));
f.print();
// Third case
*f.bar() = 23;
f.print();
return 0;
}
And this is the output: 这是输出:
5
5
5
23
Why only in the third case ptr_ changes its value? 为什么仅在第三种情况下ptr_会更改其值?
bar() returns a copy of the shared_ptr
. bar()返回
shared_ptr
的副本。
So assigning to that copy doesn't change the original shared_ptr
. 因此,分配给该副本不会更改原始的
shared_ptr
。
To make it work as you expected, you should have returned a reference to the internal pointer: 为了使其按预期工作,您应该返回对内部指针的引用:
std::shared_ptr<int>& bar()
{
return ptr_;
}
Because in the first two cases you only change the returned copy . 因为在前两种情况下,您仅更改返回的副本 。 In the third case you change what the pointer actually points to.
在第三种情况下,您可以更改指针实际指向的内容。
If you want the first two cases to work, return a reference instead. 如果希望前两种情况起作用,请返回一个引用。
这是因为bar()
应该返回对共享指针的引用才能执行您期望的操作:
std::shared_ptr<int>& bar()
Because the first two cases are using the assignment operator on a temp returned by bar(), effectively splitting it off from Foo. 由于前两种情况是在bar()返回的温度上使用赋值运算符,因此有效地将其与Foo分开。 In the last case, the dereference allows direct mutation on the shared payload.
在最后一种情况下,取消引用允许对共享有效负载进行直接更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.