Is this really legal? From "C++ templates"

V

Vladimir Jovic

Hello,

Reading this book, I found this :

int f1( int const &r )
{
return ++(int&)r; // not reasonable, but legal
}

Is this really legal? Looks like an UB to me
 
M

Michael Tsang

Stuart said:
That's like saying that this:

struct X
{
void f() {}
};

void g(X *p)
{
p->f();
}

Exhibits undefined behaviour because you can do this:

int main()
{
g(NULL);
}

***

In the original example, f1 has an implicit contract which says
something like "r must not refer to something that is physically const".
If you violate that contract, you end up with undefined behaviour. If
you don't, you don't.

The prototype makes me think that r is not changed inside f1.
 
K

Keith H Duggar

And as I understand it, the compiler is allowed to assume that r is not
changed inside f1 when optimizing code that calls f1. So for example:

void foo() {
const int r = 12;
f1(r);
int w = r; // the compiler is allowed to assign the
// value 12 to w here. Even though f1 changed r.

Walter Bright has posted a number of informative posts over the
years regarding this exact (incorrect) assumption. Here are the
general points:

1) it is legal to cast away const from a reference so a const &
is of little use to the compiler for optimization.

2) given 1) the compiler must analyze the code independent of
const & declarations.

3) the compiler can only sometimes determine legal optimizations
in the presence of references/pointers due to aliasing problems
etc. In the limited example above (with only that one reference)
it /would/ be able to do such optimizations but they would happen
regardless of the const qualifier.

4) top level const /is/ useful for optimization since it is UB to
modified a const objects (excepting mutable sub-objects). The most
common example are simple file or namespace scope constants such as:

int const TheBufferSize = 2048 ;

As to the topic of the thread, Leigh has already posted (twice)
the correct answer. Since many of you probably missed it due to
killfile filtering I've copied it below:
It is UB if the actual object that r refers to is const.

KHD
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top