简体   繁体   中英

const correctness and member reference

I have the following class:

class DataBuilder
{
public:
    DataBuilder(Data& data): data_(data){}

    //Fun modify data_, uses private methods
    void Fun(std::string name, int id) //const ?
    { 
        //calculate newInfo based on params (uses private methods)
        auto& info = data_.GetInfo();
        info = newInfo;
    }
private:
    //some private methods
    Data& data_;
};

Theoretically Fun can be const but I wonder if it is correct (logical constness) ?

Edit1 I added a very simplified Fun implementation. Edit2 Data has two GetInfo overloads:

Info& Data::GetInfo();
const Info& Data::GetInfo() const;

const in this context means "does not modify the object", which is enforced by treating the implicit this as pointer-to-const. For this reason it is common to see overloads like

Data       & getData();
Data const & getData() const;

This preserves the const ness of the calling context, and allows for modifying the Data when called in a non-const context.

In your case, you don't have a Info & Data::getInfo const; (which would be rather suspect, where does const Data get a non-const Info from?) Fun is modifying the data_ member of DataBuilder .

Aside: I would write the assignment as data.GetInfo() = newInfo;

Fun is manipulating data. So it should not be able to be declared const . The fact that you are able to do that is that apparently, data.GetInfo is declared const , yet returns a reference through which you can manipulate it's internal state. That's bad programming.

So no, this is not correct. Even in theory, Fun should not be const because it is not. It is manipulating internal state. The fact that it could be is due to bad coding. Fix that. const -correctness is something that cannot be done halfheartedly. You do it, or you don't.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM