Better practice for heap object getters / setters in C++

百般思念 提交于 2019-12-12 01:22:24

问题


I'm currently having

Type1 &GetType1() const
{
    return *this->type1;
}

void SetType1(const Type1 &type1)
{
    *this->type1 = type1;
}

and in the class definition

class Type2
{
    public:
        Type2();
        virtual ~Type2();
        Type1 &GetType1() const;
        void SetType1(const Type1 &type1);
    private:
        Type1 *type1 = nullptr;

}

And in main

 int main()
 { 
       Type2 *type2 = new Type2();
       Type1 *newType1 = new Type1();
       type2->SetType1(*newType1);

       delete type2;
       delete newType1;
  }

everywhere in my project. It seems to me that this is not a very safe method, there are cases in which the object is pointing to NULL, etc.. I would like to know if there is a better commonly accepted way to do that. Maybe opperation overloading is a good idea?


回答1:


If your class has a member pointer that can be null, then simply return the pointer from the getter function and have the user worry about the corner cases.

Type1* GetType1(){
  return this->type1;
}

void SetType1(Type1* type1) {
  this->type1 = type1;
}

If, by any chance the member cannot actually ever become null, which is a class invariant, then I think it is a good practice to return a reference, and use assertion in the getter.



来源:https://stackoverflow.com/questions/30615500/better-practice-for-heap-object-getters-setters-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!