When is it preferable to store data members as references instead of pointers?

前端 未结 5 2395
耶瑟儿~
耶瑟儿~ 2021-02-20 16:33

Let\'s say I have an object Employee_Storage that contains a database connection data member. Should this data member be stored as a pointer or as a reference?

5条回答
  •  离开以前
    2021-02-20 17:00

    I was trying to figure this out myself, so might as well post it. I conclude it doesn't seem to be a good idea to use reference data member because you could inadvertently create an alias when you go to initialize it.

    #include 
    using namespace std;
    class stuff
    {
    public:
    explicit stuff(int &a):x(a) //you have to initialize it here
    {
    //body intialization won't work
    };
    int& x; //reference data member
    };
    
    int main()
    {
    int A=100; 
    stuff B(A);//intialize B.x
    cout<

提交回复
热议问题