Question

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!

Was it helpful?

Solution

check out about it at SO and also HERE

OTHER TIPS

First, a note on vocabulary: entity objects, by definition, have identity, and so don't support assignment. I think what you mean is value objects.

Otherwise: I've generally found very little advantage in making data members const. As you've noticed, doing so makes assignment impossible, which means that they can't be const for value types. For entity objects, which can't be assigned, there is some value in making immutable members (e.g. an identifier) const, but as all accesses are in a small block of code which you control, the value is considerable less than it is for const in the public interface.

Another possibility is to define immutable types for such members. It's far more expressive to define name as an Identifier than it is to define it as an std::string, and Identifier, even if it contained only a single data member with type std::string would limit what you could do with it. (It would also facilitate changing the representation of the identifier later.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top