473,386 Members | 1,773 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

modifying a const object

I have read that using const_cast to modify an object that was originally
declared const can lead to undefined behavior.
Would this be true in the case of a user defined object containing a const
data member as in the example below, and if so, why?
In what cases can modification of an originally declared const object be
problematic?

I would appreciate any comments.

struct TestClass
{
TestClass() : m_s("123") {}
const string m_s;
};

TestClass b;
const_cast<string&>(b.m_s) = "456"; // works fine but is this acceptable ?

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jul 23 '05 #1
4 2608
Rob
Eric wrote:
I have read that using const_cast to modify an object that was
originally declared const can lead to undefined behavior.
Not precisely. Using const_cast does not, in itself, lead to
undefined behaviour. However, any process that involves (directly or
not) modifying something that is constant yields undefined behaviour.
Would this be true in the case of a user defined object containing a
const data member as in the example below, and if so, why?
Yes. The short answer is "because the standard says so".

In practice, the reason is that something which is const (whether a
class member or not) might receive special treatment from the compiler
or even from the linker. For example, the object might be physically
located in read-only memory, which makes any attempt to modify it
rather problematical.
In what cases can modification of an originally declared const object
be problematic?


As I said above, it will be problematical if the const attribute is
somehow enforced. In my example above, with a const object placed into
read-only memory, the system might elect to terminate the program if an
attempt is made to modify a const object. Or an attempt to change the
object may have no effect. Or .... the list goes on.
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jul 23 '05 #2
Eric wrote:

I have read that using const_cast to modify an object that was originally
declared const can lead to undefined behavior.
Not only 'can'. It has undefined behaviour.
Would this be true in the case of a user defined object containing a const
data member as in the example below, and if so, why?
Sure it would.

Imagine the situation:
You: This wall outlet emits 110 Volts. This voltage will never change, you can count
on it.
I: Ok. Then I will design my electrical engine for 110 volts.
You: He, he. I am going to change the 110 volts to 230 volts.
My engine: smokes

(Actually, somthing similar happend to Apollo 13)
In what cases can modification of an originally declared const object be
problematic?
Because the compiler trusts you. With const you tell the compiler:
This is the value and it is never going to change.
Thus the compiler can use the value directly instead of fetching
it from the variable in certain situations.

I would appreciate any comments.


Don't lie to your compiler.
The main usage of const_cast is when you have to interface to an external
(older) library. There might be functions, from which you know that they
want change arguments you pass to them but for some reasons those parameters
are not declared const. You have a const and with the knowledge that the
function will not attempt to change what you pass to it, you can cast the
const away in order to be able to call that function.

--
Karl Heinz Buchegger
kb******@gascad.at

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jul 23 '05 #3
Eric <sh*****@yahoo.com_nospam> schrieb:
I have read that using const_cast to modify an object that was
originally declared const can lead to undefined behavior. Would this
be true in the case of a user defined object containing a const data
member as in the example below, and if so, why? In what cases can
modification of an originally declared const object be problematic?


Rob and Karl Heinz said it right.

const_cast<> is thought to be used in the following situation: you
want to call a non-const method on a const object and you know that
the method does not modify the object. Many people forget to declare
such methods as const and so they get even into large frameworks.
Look at this:

class MyClass {
int m_i;
public:
MyClass (int i) : m_i(i) {}
int get () {return m_i;}
};

The get-method does nothing with m_i. However, it is not const. That's
why the following code will fail to compile:

int func (const MyClass& c)
{
return c.get();
}

Here you can use const_cast<>:

int func (const MyClass& c)
{
return const_cast<MyClass>(c).get();
}

You should never modify an object using const_cast<> - this will
result in dependencies on compilers and their options.

T.M.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jul 23 '05 #4
sh*****@yahoo.com_nospam (Eric) wrote (abridged):
I have read that using const_cast to modify an object that was
originally declared const can lead to undefined behavior.
Would this be true in the case of a user defined object containing a
const data member as in the example below, and if so, why?


Yes. Because the standard says so. The main reason is consistency. Some
const objects can be placed in read-only memory. That is unlikely for
member variables but the language is simpler if the same rules apply to
all, and we don't limit how clever the compiler can be.

One practical consequence is that the compiler is allowed to assume the
const object won't change after it has been constructed. In your string
example, the compiler could turn an expression like b.m_s[0] into the
constant '1', even after the assignment.

struct TestClass {
TestClass() : m_s("123") {}
const string m_s;
};

TestClass b;
if (true)
const_cast<string&>(b.m_s) = "456"; // Undefined behaviour.
assert( b.m_s[0] == '1' ); // May pass.
-- Dave Harris, Nottingham, UK.

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]

Jul 23 '05 #5

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

Similar topics

5
by: Dave | last post by:
Hello all, In the code below, I am able to modify data through the pointer-to-const DynGapRec parameter. The last two lines show this. I didn't want to create a huge message, so there's a...
5
by: jeffc | last post by:
Don't know what to put in the subject, because if this has a name I don't know it. You are modifying an existing application. You are not allowed to make more than minor changes. For example,...
12
by: pvinodhkumar | last post by:
1) char* p = "Plato"; p = 'r'; // runtime error 2) char c = "Plato"; c = 'i';// ok.Why no runtime here?Why is the contradiction? cout << c << endl;
4
by: Ney André de Mello Zunino | last post by:
Hello. The following is a summary of what I have understood from reading Stroustrup's TCPL 3rd Edition's discourse on "string literals" (5.2.2). String literals are of type const char, where n...
6
by: Tim Conkling | last post by:
I'm having difficulty tracking down a bug in my program and I'm wondering if it's due to some misuse on my part of new'd objects. Here's the situation. If anyone can shed some light on this, I'd be...
7
by: Andy Lomax | last post by:
The C99 standard contains various statements like this one (in this case, 6.5.16, assignment operator): >If an attempt is made to modify >the result of an assignment operator or to access it...
4
by: Milind | last post by:
Hi, I have a map of the type: std::map<A, B> mymap_A; std::map<X, A> mymap_X; where A, B and X are user defined types (i.e. my own clases) At the beging of the program i do a insert on...
14
by: jehugaleahsa | last post by:
I have a rather complex need. I have a class that parses web pages and extracts all relevant file addresses. It allows me to download every pdf on a web page, for instance. I would like to...
9
by: koschwitz | last post by:
Hi, I hope you guys can help me make this simple application work. I'm trying to create a form displaying 3 circles, which independently change colors 3 times after a random time period has...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.