我在修改类函数返回的智能指针的内容时遇到了一些问题。返回对指针的引用将是一种解决方案,但我担心这是一种不好的做法。
这是我的代码:
#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;
}
这是输出:
5
5
5
23
为什么只有在第三种情况下 ptr_ 才改变它的值?