Re: assignment operator and const members
On Nov 25, 5:03 pm, Jonathan Jones <clcppm-pos...@this.is.invalid>
wrote:
I think the solution to the original problem is to store the data
member in its own class, and have that class' interface manage the
access rules.
I can see where this would be desired, but it feels heavy-handed for a
small, lightweight class with just one or two data members and a
couple of methods (really just accessors). In my case, I also want a
guarantee that construction will succeed, so any heap allocation of
the data is undesirable.
You can make a generic class for these situations with assign_const()
member function in place of disabled assignment operator:
template <typename T>
class const_value
{
public:
const_value() {}
const_value (T v) : value (v) {}
operator T () const { return T; }
void assign_const (T v) { value = v; }
private:
T value;
const_value& operator = (const const_value&);
};
struct Test
{
Test& operator = (const Test& t) { data.assign_const (t.data); }
const_value<int> data;
};
Unlike assignment operator, assign_const() is very visible in the
source and is unlikely to be called accidentally. Although this
approach completely removes const optimization opportunity for
compiler, I think it is much better than your original sample (calling
destructor then placement new) which is undefined behavior according
to the standard and is quite likely to result in wrong code generated
by real world compilers.
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]