C++, Classes, Const, and strange syntax

后端 未结 8 2071
广开言路
广开言路 2020-12-18 02:14

I was re-reading c++ primer(4th ed.) today - the section on member functions and const references etc, and I came up with this wierd little program:

using st         


        
相关标签:
8条回答
  • 2020-12-18 02:49

    Objects do not become const until after their constructors finish doing their thing. So this is a pointer to non-const memory when you store it, but changes shortly after. That's why it allowed the assignment in the first place, because you did nothing wrong. That means cpp is a pointer to const, but the compiler doesn't realize that. It has no way to; you declared it non-const, after all. This is still undefined behavior, it's just not the type your compiler can ever really hope to help you catch.

    0 讨论(0)
  • 2020-12-18 02:51

    The constructor is allowed to modify the value of a const object, yes. But if it weren't, what could it do?

    Since the constructor has such access, it can "forward" it to someone else or "save" it for later. Of course, doing so might be a bad idea.

    This is one instance where the safety mechanisms of C++ do not prevent you from building an ill-formed program. C++ is anything but foolproof. So, just be careful!

    0 讨论(0)
提交回复
热议问题