C++ singleton vs completely static object

前端 未结 5 510
陌清茗
陌清茗 2020-12-13 00:12

Let say we need to have just one instance of some class in our project. There are couple ways of doing it.

I want to compare. Please can you review my understanding.

5条回答
  •  不思量自难忘°
    2020-12-13 00:57

    Another option you overlook is namespace's.

    namespace xyz {
    namespace {
        int private_variable;
    }
    
    int get_pv() {
        return private_variable;
    }
    }
    

    Functionally, this is going to be similar to your option #2, but you can't accidentally "delete" this thing. You can't accidentally create an instance of it. It is just a collection of related globally accessible data and functions. You can (as in my example) even have "private" members and functions.

    Of course the usage would be something like this:

    int x = xyz::get_pv();
    

提交回复
热议问题