Topic: Definition of const object


Author: Roman Perepelitsa<Roman.Perepelitsa@gmail.com>
Date: Tue, 6 Dec 2011 13:52:36 -0800 (PST)
Raw View
The standard mentions that modifying a const object results in
undefined behavior, but I couldn't find a definition of const object.
Can a heap-allocated object be a const object?

#include<iostream>

int main() {
   const int* p = new const int(42);
   // Modifying a const objects is undefined behavior.
   // Does p point to a const object?
   *const_cast<int*>(p) = 24;
   // Is it required to print 24?
   std::cout<<  *p<<  std::endl;
}

Roman Perepelitsa.


--
[ comp.std.c++ is moderated.  To submit articles, try posting with your ]
[ newsreader.  If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]




Author: =?ISO-8859-1?Q?Daniel_Kr=FCgler?= <daniel.kruegler@googlemail.com>
Date: Fri, 9 Dec 2011 23:54:57 -0800 (PST)
Raw View
On 2011-12-06 22:52, Roman Perepelitsa wrote:
>
> The standard mentions that modifying a const object results in
> undefined behavior, but I couldn't find a definition of const object.


There does exist a definition for a const object in [basic.type.qualifier] p1:

"[..] The term object type (1.8) includes the cv-qualifiers specified
when the object is created. The presence of a const specifier in a
decl-specifier-seq declares an object of const-qualified object type;
such object is called a const object.[..]"

> Can a heap-allocated object be a const object?


Good question. The definition above seems not to cover this case.

> #include<iostream>
>
> int main() {
>    const int* p = new const int(42);
>    // Modifying a const objects is undefined behavior.
>    // Does p point to a const object?
>    *const_cast<int*>(p) = 24;
>    // Is it required to print 24?
>    std::cout<<   *p<<   std::endl;
> }


It is hard to say whether this is well-defined, but I wouldn't rely on that;-)

I have forwarded your question to the CWG.

HTH & Greetings from Bremen,

Daniel Kr   gler




--
[ comp.std.c++ is moderated.  To submit articles, try posting with your ]
[ newsreader.  If that fails, use mailto:std-cpp-submit@vandevoorde.com ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]