C ++ to prevent class instance creation outside of a specific scope?

I have a System class that can return a pointer to the Editor class . The Editor class is created in the System class and passes pointers to System private variables. The Editor class essentially acts as an alternative interface for the internal data structures of the System .

My question is: Is there a design template that allows me to prohibit the direct creation of the Editor class , but somehow its instance inside the System ?

Thank.

+3
source share
5 answers

You can make the editor’s constructor private, which would prevent others from creating it, and then force the System friend to give it access to the constructor.

class System {
public:
    System() : editor_(new Editor()) { ... }

private:
    Editor* editor_;
}

class Editor {
    friend class System;
    Editor() { ... }
}
+6
source

You can create an abstract editor for your editor and embed the implementation in a system definition. It may even be protectedor private.

class IEditor
{
public:
   virtual int Whatever() = 0;  
};

class System
{
public:
  int foo;
  IEditor *GetEditor() { return &m_Editor; }

protected:
  class Editor 
  {
     virtual int Whatever() { return 1; }
     // etc...
  }

  Editor m_Editor;
}
+1
source

, Editor . , Editor.

0

Consider creating a copy constructor and copy assignment for both the private and the constructor. The example below shows that editor1 and editor2 can be created if these two methods are not private.

class Editor {  
private:  
    Editor();  
    friend class System;  
};  

class System {  
public:  
    Editor editor;  
};  

int main() {  
    System system;  
    Editor editor1(system.editor);  
    Editor editor2 = system.editor;  
    return 0;  
}  
0
source

Why not split the state Systeminto another class? For instance:

class SystemState {
};

class Editor {
    public:
        Editor(SystemState &state) :
            state(state) {
        }

    private:
        SystemState &state;
};

class System {
    public:
        System() :
            editor(new Editor(state)) {
        }

    private:
        SystemState state;

        Editor *editor;
};
0
source

Source: https://habr.com/ru/post/1762021/


All Articles