如何访问共享指针持有的 class 方法?

How do you access a class method that is hold by a shared pointer?

我是一名C++新手,所以我可能还没有完全理解智能指针。

我认为您可以通过 shared_ptr(在本例中,通过 weak_ptr.lock() 创建)和 ->?[=15= 访问 class 方法]

但是,由于某种原因,程序似乎在进程中终止:

class Student{
  string name;
public:
  Student(string name):name(name){}
  string get_name()const{return name;}
  virtual ~Student()=default;
};

class Lecture {
  map<string, weak_ptr<Student>> person;
  string name;
public:
  Lecture(const string& name, const Student& bi): name(name){
    weak_ptr<Student>w = std::make_shared<Student>(bi);
    person.insert({name, w});
  }

  // this is the cout-overload that does not work properly
  ostream& print(ostream& o)const{
    o<<name<<endl;
    map<string, weak_ptr<Student>>::const_iterator itr;
    for(itr=person.begin();itr!=person.end();itr++){
      // the line below is the problem
      o<<itr->second.lock()->get_name()<<endl;
    }
    return o;
  }
};

ostream& operator<<(ostream& o, const Lecture& c){
  return c.print(o);
}

这是主要的:

int main()
{
    Student Carl("Carl");
    Lecture Anatomy("Anatomy", Carl);
    cout<<Anatomy<<endl;
    cout<<"This line does not get printed anymore!";
}

不知道是什么问题

您可以这样访问:

o<<itr->second.lock()->get_name()<<endl;

现在为什么不起作用?嗯,你没有任何 shared_ptrs 指向你的对象了。所以被删了

由于对象被删除,itr->second.lock()返回了一个空指针。然后你尝试使用空指针,这导致你的程序崩溃。