There is such code:

int main() { unique_ptr<ProjectModel> model = unique_ptr<ProjectModel>(new ProjectModel(2)); unique_ptr<ProjectControl> control = unique_ptr<ProjectControl>(new ProjectControl(*model)); unique_ptr<ProjectView> view = unique_ptr<ProjectView>(new ProjectView(*control)); return 0; } 

When closing the program, an exception crashes: read access violation What could be the problem? I read that in main you always need to catch exceptions, is it true and how correct is it?

I fixed an exception pointing to the destructor model, but now it throws a general exception to read access violation. I have the following code:

 class ProjectView { public: ProjectView::ProjectView(ProjectControl& control) : m_control(&control) {} private: const std::shared_ptr<ProjectControl> m_control; } class ProjectControl { public: ProjectControl::ProjectControl(ProjectModel& model) : m_model(&model) {} private: const std::shared_ptr<ProjectModel> m_model; } 
  • In general, your code looks like the misuse of unique_ptr. At unique_ptr there can be only 1 owner, you should use shared_ptr. - Pavel Mayorov
  • Check the destructors of your classes, most likely the objects are destroyed in the wrong order as you would like. As a result, when deleting one object, it tries to use the data of another already deleted. To advise something more specific, give a minimal reproducible example . - αλεχολυτ
  • @PavelMayorov plugging holes through shared_ptr not the best way, although probably the easiest. - αλεχολυτ
  • @alexolut, in fact, there are few options - either to give up smart pointers, or use shared_ptr . Because unique_ptr doesn’t fit here, storing a reference to an object that unique_ptr owns unique_ptr is a gross mistake. - Pavel Mayorov
  • The error throws into the ProjectModel destructor, but there is nothing there, all my work happens with smart pointers. - Sergey

1 answer 1

You have one object of type ProjectModel whose memory is handled by unique_ptr . Then you pass this object by reference to the constructor of the ProjectControl class, which now creates another smart pointer of the type shared_ptr , but points to the same object. That is, the life cycle of a single object is controlled by two smart pointers. Accordingly, twice there is a deletion. Similarly with the ProjectView class.

You need to decide who should manage the memory of the object and in what form - using exclusive ( unique_ptr ) or joint ( shared_ptr ) ownership.

  • Thank you very much. I'll fix it. - Sergey