Vector of const objects giving compile error

Items in a vector must be assignable (or, in more recent versions of the standard, movable). const objects aren’t assignable, so attempting to store them in a vector will fail (or at least can fail — the code is invalid, but a compiler is free to accept it anyway, if it so chooses, though most programmers would generally prefer that invalid code be rejected).

I suppose for the truly pedantic, if you wanted to badly enough, you could define a type that was assignable despite being const, something like this:

class ugly { 
    mutable int x;
public:
    ugly const &operator=(ugly const &u) const { 
        x = u.x;
        return *this;
    }
};

I believe you should be able to store items of this type in a vector even though they’re const. A quick test of creating a vector of these succeeds with VC++. This failed with some older compilers (e.g., failed with g++ 4.8.1), but works with reasonably recent ones (VC++ back to at least 2015, g++ back to at least 5.4 and clang++ back to at least 4.0–though I haven’t tried to track down the first version of each that supported it).

For a current compiler, a type that supported moving const objects would probably work just as well. But, just in case it wasn’t obvious: this is allowing you to modify an object even though it’s marked const. That’s clearly a direct violation of any reasonable user’s expectations, so it’s mostly a problem, not a solution.

Leave a Comment