mercredi 5 juillet 2017

Why must accessor functions be const? Where is the vulnerability?

Professors hammered it into my head when I was in school, associates have jumped down my throat for it on code reviews, and it's in pretty much every C++ textbook out there: accessor (aka selector or getter) methods must be marked const. If it doesn't change or mutate the data, then mark it const.

Why? How could the invocation of an accessor modify the private data?

In the following example, I have set up a simple class and one accessor. How can getBrand() be used to modify the private data? In my eyes, it can't; so why do we need to mark it const?

In other words, am I correct in saying that it is impossible for getBrand() to be used, in practice, to mutate a private property?

Minimal, complete, verifiable example:

#include <iostream>
#include <string>

class Cheese {
public:
    Cheese(std::string brand):brand_(brand) {}
    std::string getBrand() { return brand_; } // Intentionally not marked const
private:
    std::string brand_;
};

int main() {
    Cheese cheddar("Cabot clothbound");
    std::cout << "Brand: " << cheddar.getBrand() << std::endl;

    std::cout << "Press any key to exit ";
    std::cin.get();
    std::cout << "\n";
    return 0;
}

Output

Brand: Cabot clothbound
Press any key to exit 

Aucun commentaire:

Enregistrer un commentaire