Effective C++ 条款28

避免返回handles指向对象内部成分

本节作者讲述的知识核心是对于一个类来说,应该避免类返回自己内部的私有数据。
例如以下:

class Point{
public:
    Point(int x, int y);
    ……
    void setX(int newVal);
    void setY(int newVal);
    ……
};

struct RectData{
    Point ulhc;//upper left-hand corner
    point lrhc;//lower right-hand corner
};

class Rectangle{
……
private:
    std::tr1::shared<RectData> pData;
};

class Rectangle{
……
public:
    Point& upperLeft()const{return pData->ulhc;}//应该尽量避免
    Point& lowerRight()const{return pData->lrhc;}//应该尽量避免
};

为什么要避免这样的调用呢?非常easy,为了避免非法改动被调用的私有数据

例如以下:

Point coord1(0,0);
Point coord1(100,100);
const Rectangle rec(coord1,coord2);
rec.upperLeft().setX(50);//被非法改动,并且此类行为不易被察觉

有什么解决的方法?
解决的方法例如以下:

class Rectangle{
……
public:
    const Point& upperLeft()const{return pData->ulhc;}
    const Point& lowerRight()const{return pData->lrhc;}
};

上述採用的方式是声明函数返回const对象。

可是,这样的方式也不能根治问题,例如以下:

class GUIObject{……}。
const Rectangle boundingBox(const GUIObject& obj);

GUIObject* pgo;
const Point* pUpperLeft=&(boundingBox(*pgo).upperLeft());

调用boundingBox获得一个新的、暂时的Rectangle对象,暂时对象没有名字。暂且成为temp,随后upperLeft作用于temp身上,返回一个reference指向temp的一个内部成分。于是,pUpperLeft指向这个Point对象。问题出在temp是一个暂时对象。当这个语句结束后,暂时对象便会析构。这时pUpperLeft指向一个不再存在的对象。pUpperLeft变成空悬、虚吊(dangling)。

总结:
避免返回handles(reference、指针、迭代器)指向对象内部。遵守这个条款能够添加封装性,帮助const成员函数的行为像个const,并将发生“虚吊号码牌”(dangling handles)的风险降到最低。

posted on 2017-06-15 14:51  yjbjingcha  阅读(243)  评论(0编辑  收藏  举报

导航