C ++中堆对象获取器/设置器的更好实践 [英] Better practice for heap object getters / setters in C++
问题描述
我目前有
Type1 &GetType1() const
{
return *this->type1;
}
void SetType1(const Type1 &type1)
{
*this->type1 = type1;
}
以及类定义中
class Type2
{
public:
Type2();
virtual ~Type2();
Type1 &GetType1() const;
void SetType1(const Type1 &type1);
private:
Type1 *type1 = nullptr;
}
主要
int main()
{
Type2 *type2 = new Type2();
Type1 *newType1 = new Type1();
type2->SetType1(*newType1);
delete type2;
delete newType1;
}
我项目中的任何地方.在我看来这不是一个非常安全的方法,在某些情况下该对象指向NULL等. 我想知道是否有更好的普遍接受的方法可以做到这一点.也许操作超载是个好主意?
如果您的类的成员指针可以为null,则只需从getter函数返回该指针,并让用户担心出现极端情况.
Type1* GetType1(){
return this->type1;
}
void SetType1(Type1* type1) {
this->type1 = type1;
}
如果该成员有可能实际上无法变为null(这是类不变的),那么我认为返回引用并在getter中使用断言是一个好习惯.
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?
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.
这篇关于C ++中堆对象获取器/设置器的更好实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!