如何通过共享 ptr 到共享 ptr 访问类的成员函数?

scs*_*rin 3 c++ pointers shared-ptr

我有两个类,fooand bar,其中bar包含指向 的指针foo,如下所示。

#include<iostream>
#include<memory>
class foo {
private:
  int num{4};
public:
  void sum(const int& to_add) {num += to_add;}
  int access_num() {return num;}
};
class bar {
private:
  std::shared_ptr<foo> ptr;
public:
  void change_ptr(foo& f) {
    auto new_ptr = std::make_shared<foo>(f);
    ptr = std::move(new_ptr);
  }
  std::shared_ptr<foo> access_ptr() { return ptr; }
};
Run Code Online (Sandbox Code Playgroud)

如果我想通过 in 中的指针执行 的成员函数sum(),我该怎么做?目前,正在尝试foobar

  foo f;
  std::shared_ptr<bar> bar_ptr = std::make_shared<bar>();
  bar_ptr->change_ptr(f);
  // Add three to the int stored in f via the pointer
  bar_ptr->access_ptr()->sum(3);
  std::cout << f.access_num() << std::endl;
Run Code Online (Sandbox Code Playgroud)

不工作,输出4。

Vas*_*lij 5

这段代码

void change_ptr(foo& f) {
    auto new_ptr = std::make_shared<foo>(f); // copy constructor
    ptr = std::move(new_ptr);
}  
Run Code Online (Sandbox Code Playgroud)

调用复制构造函数foo在堆上创建一个实例并使用std::shared_ptr. 如果删除 foo 声明中的复制构造函数,则可以检查它。代码不会编译。请注意,您必须至少提供一个默认构造函数,因为如果您显式删除了复制构造函数,则零规则不起作用。

class foo {
private:
    int num{4};
public:
    foo() = default;
    foo(foo const &other) = delete;
    void sum(const int& to_add) {num += to_add;}
    int access_num() {return num;}
};
Run Code Online (Sandbox Code Playgroud)

foo f是存储在堆栈中的自动变量。用 来管理它没有多大用处std::shared_ptr。您可能需要的是在堆上创建一个 foo 实例并使用 std::shared_ptr 来处理它:

#include<memory>

class foo {
private:
    int num{4};
public:
    void sum(const int& to_add) {num += to_add;}
    int access_num() {return num;}
};

class bar {
private:
    std::shared_ptr<foo> ptr;
public:
    void change_ptr(std::shared_ptr<foo> f) {
        ptr = std::move(f); // f is already a copy, so we can safely move it
    }
    std::shared_ptr<foo> access_ptr() { return ptr; }
};

int main() {
    auto f = std::make_shared<foo>();
    std::shared_ptr<bar> bar_ptr = std::make_shared<bar>();
    bar_ptr->change_ptr(f);
    bar_ptr->access_ptr()->sum(3);
    std::cout << f->access_num() << std::endl;
}
Run Code Online (Sandbox Code Playgroud)