问题
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