KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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. Consider the class with const member: class A { public: const int c; // must not be modified! A(int c) : c(c) {} A(const A& copy) : c(copy.c) { } // No assignment operator }; I want to have an assignment operator but I do not want to use const_cast like in the following code from one of the answers: A& operator=(const A& assign) { *const_cast<int*> (&c)= assign.c; // very very bad, IMHO, it is undefined behavior return *this; } My solution is // Custom-defined assignment operator A& operator=(const A& right) { if (this == &right) return *this; // manually call the destructor of the old left-side object // (`this`) in the assignment operation to clean it up this->~A(); // use "placement new" syntax to copy-construct a new `A` // object from `right` into left (at address `this`) new (this) A(right); return *this; } Do I have undefined behavior (UB)? What would be a solution without UB?
Tags (comma-separated)
Save Edits
Cancel