I answered the question about std::vector of objects and const-correctness, and received a comment about undefined behavior. I do not agree and therefore I have a question.<
In absence of other (non-const
) members, this doesn't make any sense at all, regardless of undefined behavior or not.
A& operator=(const A& assign)
{
*const_cast (&c)= assign.c; // very very bad, IMHO, it is UB
return *this;
}
AFAIK, this is no undefined behavior happening here because c
is not a static const
instance, or you couldn't invoke the copy-assignment operator. However, const_cast
should ring a bell and tell you something is wrong. const_cast
was primarily designed to work around non const
-correct APIs, and it doesn't seem to be the case here.
Also, in the following snippet:
A& operator=(const A& right)
{
if (this == &right) return *this;
this->~A()
new (this) A(right);
return *this;
}
You have two major risks, the 1st of which has already been pointed out.
A
and a virtual destructor, this will lead to only partial reconstruction of the original instance.new(this) A(right);
throws an exception, your object will be destroyed twice. In this particular case, it won't be a problem, but if you happen to have significant cleanup, you're going to regret it.Edit: if your class has this const
member that is not considered "state" in your object (i.e. it is some sort of ID used for tracking instances and is not part of comparisons in operator==
and the like), then the following might make sense:
A& operator=(const A& assign)
{
// Copy all but `const` member `c`.
// ...
return *this;
}