Search code examples
c++constantscompiler-optimizationconst-correctnessconstruction

C++ const-correctness and const members


Possible Duplicate:
Does const-correctness give the compiler more room for optimization?

During the last few weeks, I have developed a thing for making all my non-static members const if possible in order to avoid unintended programming errors. However, this practice provides some enormous drawbacks, especially for entity objects, since e.g. no one will ever be able to call an assignment operator anymore, should they chose to aggregate such an entity object directly rather than using a pointer.

My question is as to whether this const member philosophy even provides any compiler optimization bonuses.

class User {
public:
    User(const std::string &, const std::vector<unsigned char> &);
    ~User();
    const std::string &getName() const;
    const std::vector<unsigned char> &getPasswordHash() const;
private:
    std::string name;
    std::vector<unsigned char> passwordHash;
};

Would it provide my compiler with any significant optimization possibilities if this class' members were const? Given the fact that other classes usually would usually aggregate non-const User objects, but almost all my algorithms would accept a const User &?

So do the const members provide any significant optimization opportunities over the already present const User & mentality? And would it justify using const User * aggregations and reconstruct the objects on change rather than using the assignment operator?

Thanks for some quick remarks!


Solution

  • check out about it at SO and also HERE