Same function with const and without - When and why?

后端 未结 7 1768
终归单人心
终归单人心 2020-12-01 11:44
T& f() { // some code ... }
const T& f() const { // some code ... }

I\'ve seen this a couple of times now (in the introductory book I\'ve b

7条回答
  •  借酒劲吻你
    2020-12-01 12:37

    There is a very nice example in the Qt framework.

    Take a look at the QImage class.

    There are two public functions:

    const uchar* scanLine (int i) const;
    uchar* scanLine (int i);
    

    The first one is for read access only. The second one is for the case that you want to modify the scan line.

    Why is this distinction important? Because Qt uses implicit data sharing. This means, QImage does not immediately perform a deep copy if you do something like this:

    QImage i1, i2;
    i1.load("image.bmp");
    i2 = i1;                        // i1 and i2 share data
    

    Instead, the data is copied only and only if you call a function that actually modifies one of the two images, like the non-const scanLine.

提交回复
热议问题