Effecitive C++ 28. Avoid returning "handle" to object internals

class Point {
public:
    Point(int valx, int valy) {
        x = valx;
        y = valy;
    }

    void setX(int newVal) {
        x = newVal;
    }   

    void setY(int newVal) {
        y = newVal;
    }

private:
    int x;
    int y;
};

struct RectData {
    Point ulhc; // upper left-hand corner
    Point lrhc;
};
class Rectangle {
public:
    Rectangle(Point& val1, Point& val2) {
        pData->ulhc = val1;
        pData->lrhc = val2;
    }

    Point& upperLeft() { return pData->ulhc; }
    Point& lowerRight() { return pData->lrhc; }
private:
    std::tr1::shared_ptr<RectData> pData;
};

Point coord1(0, 0);
Point coord2(100, 100);
const Rectangle rec(coord1, coord2);
rec.upperLeft().setX(50);
class GUIObject { ... }
const Rectangle
    boundingBox(const GUIOject& obj);

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

boundingBox’s return value -temp-will be destroyed, and that will indirectly lead to the destruction of temp’s Points.

可运行

#include <memory>
#include <iostream>

class Point {
public:
    Point(int xVal, int yVal) : x(xVal), y(yVal) { }

    void setX(int newVal) {
        x = newVal;
    }

    void setY(int newVal) {
        y = newVal;
    }
    int getX() {
        return x;
    }

private:
    int x;
    int y;
};

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

class Rectangle {
public:
    Rectangle(Point& val1, Point& val2) {
        RectData* data = static_cast<RectData*> (malloc(sizeof(RectData)));
        data->ulhc = val1;
        data->lrhc = val2;
        pData = static_cast<std::shared_ptr<RectData> > (data);
    }

    Point& upperLeft() const { return pData->ulhc; }
    Point& lowerRight() { return pData->lrhc; }
private:
    std::tr1::shared_ptr<RectData> pData;
};
int main() {
    Point coord1(0, 0);
    Point coord2(100, 100);

    const Rectangle rec(coord1, coord2);


    rec.upperLeft().setX(50);

    std::cout << rec.upperLeft().getX();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值