Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a class with const data members in a vector

Given a class like this:

class Foo
{
   const int a;
};

Is it possible to put that class in a vector? When I try, my compiler tells me it can't use the default assignment operator. I try to write my own, but googling around tells me that it's impossible to write an assignment operator for a class with const data members. One post I found said that "if you made [the data member] const that means you don't want assignment to happen in the first place." This makes sense. I've written a class with const data members, and I never intended on using assignment on it, but apparently I need assignment to put it in a vector. Is there a way around this that still preserves const-correctness?

like image 628
Max Avatar asked May 26 '10 22:05

Max


1 Answers

I've written a class with const data members, and I never intended on using assignment on it, but apparently I need assignment to put it in a vector. Is there a way around this that still preserves const-correctness?

You have to ask whether the following constraint still holds

a = b;
 /* a is now equivalent to b */

If this constraint is not true for a and b being of type Foo (you have to define the semantics of what "equivalent" means!), then you just cannot put Foo into a Standard container. For example, auto_ptr cannot be put into Standard containers because it violates that requirement.

If you can say about your type that it satisfies this constraint (for example if the const member does not in any way participate to the value of your object, but then consider making it a static data member anyway), then you can write your own assignment operator

class Foo
{
   const int a;
public:
   Foo &operator=(Foo const& f) {
     /* don't assign to "a" */
     return *this;
   }
};

But think twice!. To me, it looks like that your type does not satisfy the constraint!

like image 72
Johannes Schaub - litb Avatar answered Oct 23 '22 13:10

Johannes Schaub - litb