Should classes be copy-assignable?

Well, basically I have a class which aggregates some data together - a score. At first, I was going to make the class completely immutable (const data members, private copy assignment operator, etc).

However, one thing is that I am trying to keep a sorted std::vector of them, as I add them one at a time. Now, to do this, I'm considering two options.

The first is that rather than a std::vector<score>, use a std::vector<score*>. This would allow me to keep the vector sorted, at the cost of pointless allocation of the objects. Also, would add in a loop to deallocate them at the end.

The second is to reconsider making them completely immutable. While I would still prevent the user from changing the internals normally, I would allow them to be copy-assigned, move-assigned, and swapped. Outside of the fact that it sacrifices immutability, I don't really see any major problems with this, because the objects are small and aren't likely to cause any kind of bottlenecks being moved around inside the vector.

Is there a better way to deal with immutable objects in C++ in situations like this?
So, basically your problem is that you want a completely immutable object in a vector, but due to the limitations of the vector you can't. Well, you can. Rather than having it copy-assignable, why not have it just move-assignable, as that way the class can be shifted in memory as the sorting algorithm's need, but won't be copied all over the place. So your class should look like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Score {
    public:
        Score() { /* implement */ }
        Score(Score&& other) { /* implement */ }
        Score& operator=(Score&& other) { /* implement */ }

        // various immutable getter funcs, e.g.
        int getVal() const { return _val; }
        const std::string& getOtherVal() const { return _otherval; } 

    private:
        // various objects, e.g.
        int _val;
        std::string _otherval;
    
        Score(const Score& other) = delete;
        Score& operator=(const Score& other) = delete;
};


If you did decide to use a vector of pointers to score, though, consider using a std::unique_ptr instead to remove the burden of forcing you to remember to deallocate them at the end.
Topic archived. No new replies allowed.