zoukankan      html  css  js  c++  java
  • Effective C++ 笔记 —— Item 28: Avoid returning "handles" to object internals.

    Suppose you’re working on an application involving rectangles. Each rectangle can be represented by its upper left corner and its lower right corner. To keep a Rectangle object small, you might decide that the points defining its extent shouldn‘t be stored in the Rectangle itself, but rather in an auxiliary struct that the Rectangle points to:

    class Point 
    { // class for representing points
    public:
        Point(int x, int y);
        // ...
        void setX(int newVal);
        void setY(int newVal);
        // ...
    };
    
    struct RectData 
    {
    // Point data for a Rectangle
    Point ulhc; // ulhc = “ upper left-hand corner”
    Point lrhc; // lrhc = “ lower right-hand corner”
    };
    
    class Rectangle {
    // ...
    private:
        std::tr1::shared_ptr<RectData> pData; // see Item 13 for info on
    };
    
    class Rectangle 
    {
    public:
        // ...
        Point& upperLeft() const { return pData->ulhc; }
        Point& lowerRight() const { return pData->lrhc; }
        // ...
    };

    This design will compile, but it‘s wrong. In fact, it's self-contradictory. On the one hand, upperLeft and lowerRight are declared to be const member functions, because they are designed only to offer clients a way to learn what the Rectangle’' points are, not to let clients modify the Rectangle (see Item 3). On the other hand, both functions return references to private internal data — references that callers can use to modify that internal data!

    Both of the problems we've identified for those functions can be eliminated by simply applying const to their return types:

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

    Even so, upperLeft and lowerRight are still returning handles to an object's internals, and that can be problematic in other ways. In particular, it can lead to dangling handles: handles that refer to parts of objects that don’t exist any longer. The most common source of such disappearing objects are function return values. For example, consider a function that returns the bounding box for a GUI object in the form of a rectangle:

    class GUIObject { /*...*/ };
    const Rectangle // returns a rectangle by
    boundingBox(const GUIObject& obj); // value; see Item 3 for why return type is const

    Now consider how a client might use this function:

    GUIObject *pgo; // make pgo point to some GUIObject
    
    const Point *pUpperLeft = &(boundingBox(*pgo).upperLeft()); // get a ptr to the upper left point of its bounding box

    The call to boundingBox will return a new, temporary Rectangle object. That object doesn’t have a name, so let's call it temp. upperLeft will then be called on temp, and that call will return a reference to an internal part of temp, in particular, to one of the Points making it up. pUpperLeft will then point to that Point object. So far, so good, but we’re not done yet, because at the end of the statement, boundingBox’s return value — temp — will be destroyed, and that will indirectly lead to the destruction of temp’s Points. That, in turn, will leave pUpperLeft pointing to an object that no longer exists; pUpperLeft will dangle by the end of the statement that created it!

    This is why any function that returns a handle to an internal part of the object is dangerous. It doesn’t matter whether the handle is a pointer, a reference, or an iterator. It doesn't matter whether it’s qualified with const. It doesn't matter whether the member function returning the handle is itself const. All that matters is that a handle is being returned, because once that's being done, you run the risk that the handle will outlive the object it refers to.

    Things to Remember :

    • Avoid returning handles (references, pointers, or iterators) to object internals. Not returning handles increases encapsulation, helps const member functions act const, and minimizes the creation of dangling handles.
  • 相关阅读:
    如何优雅地用Redis实现分布式锁?
    redis 持久化有几种方式?
    怎么保证缓存和数据库数据的一致性?
    jedis 和 redisson 有哪些区别?
    redis支持哪些数据类型?redis命令大全
    什么是redis的缓存雪崩与缓存穿透?如何解决?
    redis 为什么是单线程的?
    什么是memecache?redis 和 memecache 有什么区别?
    Redis入门到精通(九)——Redis数据库基本操作(切换数据库,数据移动,删除数据)
    Redis入门到精通(八)——key通用指令基本操作、key扩展操作(时效性控制、查询模式)、key其他操作(为key改名)
  • 原文地址:https://www.cnblogs.com/zoneofmine/p/15248584.html
Copyright © 2011-2022 走看看