473,698 Members | 2,393 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

does this have undefined behaviour

Consider the following code:

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
const double& ref = 100;
double& d = const_cast<doub le&>(ref);
cout << d << endl;
d = 1.1;
cout << ref << endl;

return EXIT_SUCCESS;
}

In both g++ and VC++ 2005 Express Edition, the output is
100
1.1

But my doubt is: "does using 'd' invoke undefined behavior or is it
valid."

double& d = const_cast<doub le&>(ref);

Kindly clarify.

Thanks
V.Subramanian
Dec 21 '07
10 1797
Rahul wrote:
>The temporary to which 'ref' is bound is not a const object. It
is perfectly OK to change its value. Whether it makes sense to
do so or not is another question, but the idea is the same as in

I think, as the temp object is that of an in-built type, it is fine.
But had it been that of a custom type, the temp object would have been
an constant object...
It's the other way around. It could work with a class type.

To provide lost context, we consider code like this:

const double& ref = 100; // *
double& d = const_cast<doub le&>(ref);
d = 1.1;

Clearly, line (*) is the important line. Its meaning is governed by
[8.3.5/5], which is too long to quote in full, so I cut out irrelevant
parts:

A reference to type ?cv1 T1? is initialized by an expression of type
?cv2 T2? as follows:
? If the initializer expression
? is an lvalue ...
? has a class type ... and can be implicitly converted to an lvalue ...
? Otherwise, the reference shall be to a non-volatile const type ...
? If the initializer expression is an rvalue, with T2 a class type, ...
? Otherwise, a temporary of type ?cv1 T1? is created and initialized
from the initializer expression using the rules for a non-reference
copy initialization (8.5). The reference is then bound to the
temporary. If T1 is reference-related to T2, cv1 must be the same
cv-qualification as, or greater cvqualification than, cv2; otherwise,
the program is ill-formed.

In line (*), the initializer is an rvalue not convertible to an lvalue. That
puts us in the first "Otherwise" item. Also, it is not of class type, which
puts us in the "Otherwise" subitem. The provision then states that the
const reference is bound to a temporary of type cv1 T1 (in our case that is
a temporary of type const double). Modifying that temporary under a
different handle is undefined behavior.
Now consider a class type ClassType:

const ClassType & ref = some_expression _of_ClassType;
ClassType & handle = const_cast< ClassType& >( ref );
handle = some_other_expr ession;

We then have the following verions of [8.5.3/5]:

A reference to type ?cv1 T1? is initialized by an expression of type
?cv2 T2? as follows:
? If the initializer expression
? is an lvalue ...
? has a class type ... and can be implicitly converted to an lvalue ...
? Otherwise, the reference shall be to a non-volatile const type ...
? If the initializer expression is an rvalue, with T2 a class type,
and ?cv1 T1? is reference-compatible with ?cv2 T2,? the reference is
bound in one of the following ways (the choice is
implementation-defined):
? The reference is bound to the object represented by the rvalue (see
3.10) or to a sub-object within that object.
? A temporary of type ?cv1 T2? [sic] is created, and a constructor is
called to copy the entire rvalue object into the temporary. The
reference is bound to the temporary or to a sub-object
within the temporary.
...
...

In this case, depending on the choice of the implementation, the reference
is either bound to a temporary of type ClassType or of type const ClassType
(if the implementation chose the second alternative). Therefore, it is
implementation-defined whether the code has undefined behavior for class
types. (I have a vague recollection that the second alternative is slanted
for elimination in the next version of the standard. In that case, the code
would have well-defined behavior for class types and undefined behavior for
built-in types.)
Best

Kai-Uwe Bux
Dec 27 '07 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
5985
by: puzzlecracker | last post by:
interesting case: class MyString{ char * strRep; // initialized to char array public: ~MyString(){delete strRep;} //why would this work // just like 'delete strRep;' };
11
7614
by: becte | last post by:
What does the standard say about f(x++) ? 1. x is incremented and then the that value is used in function f, i.e. x++; f(x); 2. the value of x (before ++) is send to f and after returning. x is increased, i.e f(x); x++; 3. undefined behavior, it is different for different compilers I encountered the problem when I was porting code (not written by me) from AIX to Linux. Visual age and gcc gave different results (2 and 1 respectively),...
1
1833
by: David Resnick | last post by:
I had a problem going from gcc 2.96 to gcc 3.2.3 and narrowed it down to the following code. The question is whether the problem is undefined behavior on the code's part or a compiler bug. #include <stdlib.h> #include <stdio.h> struct frob { char a; int b;
29
3357
by: Vol | last post by:
I think 'atan' can get the angle but it is not the four quadrant angle. Is there any function that i can get the angle from -pi to pi? or I have to use some if ... else? I know in Matlab, we use 'atan2( )' Also, is there any function to get the round value, similar with floor and ceil, such like: round(3.1) = 3 round(3.6) = 4
7
1650
by: Daniel Rudy | last post by:
Hello, I have a peice of code that I'm making an attempt to code. The problem is that I need to return an arbitrary number of char strings. int function(char *fname, int *dcount, char *data) Would this work? If so, then how to you load the data into data? Malloc?
9
2470
by: ziman137 | last post by:
Hi all, The results from following codes got me a bit confused. #include <stdio.h> #include <iostream> using namespace std; struct A {
89
6041
by: Cuthbert | last post by:
After compiling the source code with gcc v.4.1.1, I got a warning message: "/tmp/ccixzSIL.o: In function 'main';ex.c: (.text+0x9a): warning: the 'gets' function is dangerous and should not be used." Could anybody tell me why gets() function is dangerous?? Thank you very much. Cuthbert
26
2182
by: Frederick Gotham | last post by:
I have a general idea of the different kinds of behaviour described by the C Standard, such as: (1) Well-defined behaviour: int a = 2, b = 3; int c = a + b; (Jist: The code will work perfectly.)
7
318
by: rsk | last post by:
char *i_reg_fname = "none"; -- Message posted using http://www.talkaboutprogramming.com/group/comp.lang.c/ More information at http://www.talkaboutprogramming.com/faq.html
0
8676
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9161
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8867
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4370
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4619
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3050
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2332
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2006
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.