const member and assignment operator. How to avoid the undefined behavior?

前端 未结 8 1696
别跟我提以往
别跟我提以往 2020-12-05 17:14

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.<

8条回答
  •  眼角桃花
    2020-12-05 18:00

    How can you possibly assign to an A if it has a const member? You're trying to accomplish something that's fundamentally impossible. Your solution has no new behaviour over the original, which is not necessarily UB but yours most definitely is.

    The simple fact is, you're changing a const member. You either need to un-const your member, or ditch the assignment operator. There is no solution to your problem- it's a total contradiction.

    Edit for more clarity:

    Const cast does not always introduce undefined behaviour. You, however, most certainly did. Apart from anything else, it is undefined not to call all destructors- and you didn't even call the right one- before you placed into it unless you knew for certain that T is a POD class. In addition, there's owch-time undefined behaviours involved with various forms of inheritance.

    You do invoke undefined behaviour, and you can avoid this by not trying to assign to a const object.

提交回复
热议问题