473,609 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const_cast versus compiler optimization

Hello,

I wonder if and in what cases casting const away by a const_cast can be
dangerous. In one place the only way I can imagine to realize a pretty
nice feature is casting away const. Now I wonder if this is dangerous. I
have something like that:

const Object &
Object::dummy(c onst AType &a) const
{
Object &refThis = const_cast<Obje ct &>(*this);
AType &refA = const_cast<ATyp e &>(rhs);
refThis.member = a.member();
...
}

Are there situations, where these constructs are dangerous?
I know, this code is ugly. But the realized feature is worth it.

regards,
Alex
Jul 23 '05 #1
6 1926
Alexander Stippler wrote:
I wonder if and in what cases casting const away by a const_cast can be
dangerous. In one place the only way I can imagine to realize a pretty
nice feature is casting away const. Now I wonder if this is dangerous.
It is no more (and no less) dangerous than any other undefined behaviour.
I
have something like that:

const Object &
Object::dummy(c onst AType &a) const
{
Object &refThis = const_cast<Obje ct &>(*this);
AType &refA = const_cast<ATyp e &>(rhs);
refThis.member = a.member();
...
}

Are there situations, where these constructs are dangerous?
I know, this code is ugly. But the realized feature is worth it.


It's not just ugly. It's simply wrong. You should at least be consistent
with your names. Did you mean

const Object &
Object::dummy(c onst AType &a) const
{
Object &refThis = const_cast<Obje ct &>(*this);
AType &refA = const_cast<ATyp e &>(a);
refThis.member = refA.member();
...
}

?

To answer your question, it's dangerous where 'a' or 'this' were _created_
as 'const'. The compiler is allowed to place any parts of the object in
read-only part of program memory when the object is declared 'const'.
Assigning to 'refThis.member ' causes undefined behaviour.

V
Jul 23 '05 #2

"Alexander Stippler" <st**@mathemati k.uni-ulm.de> wrote in message
news:20******** ************@ne ws.uni-ulm.de...
Hello,

I wonder if and in what cases casting const away by a const_cast can be
dangerous. In one place the only way I can imagine to realize a pretty
nice feature is casting away const. Now I wonder if this is dangerous. I
have something like that:

const Object &
Object::dummy(c onst AType &a) const
{
Object &refThis = const_cast<Obje ct &>(*this);
AType &refA = const_cast<ATyp e &>(rhs);
refThis.member = a.member();
...
}

Are there situations, where these constructs are dangerous?
I know, this code is ugly. But the realized feature is worth it.


Why would you make the function const if it's going to modify the object
it's called on? And why use the local references at all? It looks like all
you're doing is this:

const Object & Object::dummy(c onst AType &a)
{
member = a.member();
...
}

-Howard
Jul 23 '05 #3

"Howard" <al*****@hotmai l.com> wrote in message
news:Dp******** *************@b gtnsc04-news.ops.worldn et.att.net...

"Alexander Stippler" <st**@mathemati k.uni-ulm.de> wrote in message
news:20******** ************@ne ws.uni-ulm.de...
Hello,

I wonder if and in what cases casting const away by a const_cast can be
dangerous. In one place the only way I can imagine to realize a pretty
nice feature is casting away const. Now I wonder if this is dangerous. I
have something like that:

const Object &
Object::dummy(c onst AType &a) const
{
Object &refThis = const_cast<Obje ct &>(*this);
AType &refA = const_cast<ATyp e &>(rhs);
refThis.member = a.member();
...
}

Are there situations, where these constructs are dangerous?
I know, this code is ugly. But the realized feature is worth it.


Why would you make the function const if it's going to modify the object
it's called on? And why use the local references at all? It looks like
all you're doing is this:

const Object & Object::dummy(c onst AType &a)
{
member = a.member();
...
}


I should have said, "it looks like all you're TRYING to do is this:"

-Howard

Jul 23 '05 #4
Howard wrote:

Why would you make the function const if it's going to modify the object
it's called on? And why use the local references at all? It looks like all
you're doing is this:

const Object & Object::dummy(c onst AType &a)
{
member = a.member();
...
}


Possibly he's creating a functor. Of course, the correct way to do that
is to make the particular item to be updated mutable.
Jul 23 '05 #5
...
Why would you make the function const if it's going to modify the
object it's called on? And why use the local references at all? It
looks like all you're doing is this:

const Object & Object::dummy(c onst AType &a)
{
member = a.member();
...
}


I should have said, "it looks like all you're TRYING to do is this:"

-Howard


Not really. It's hard to desribe in a few lines. So I use an example:
I want objects, which refer to other objects of the same type, like the
following by a member function:

Object &
referTo(Object &rhs);

Object oneO, otherO;
oneO.referTo(ot herO);

At that point, oneO is a "pointer into" otherO. No problem, as long as
otherO is not const. But if otherO were const, I would like to have oneO
refer to otherO, but oneO should not be able to change otherO. So I make
oneO const, but then I need the const_cast ...
An abuse of const, one might say and he would probably be right. What I
want to implement is a reference, where the referenced object is const (
not modifiable through the reference), not the reference object. Why not
a type of its own for the references? Because all classes are template
classes and there would be plenty of complications, because the
reference shall be used just like the original object and type
conversions for templates together with instantiation ...
Tried to explain my motivation, but must sounds strange and like bad
design, or?
But I have now found a standard conform solution :-).

regards,
Alex
Jul 23 '05 #6
Alexander Stippler wrote:
Are there situations, where these constructs are dangerous?


Yes: if you have any doubt, is dangerous. You must use a cast only when you
are sure that is safe. The casts tell the compiler: "I really know what I'm
doing".

The key is: don't cast away constness to modify an object that is const.

--
Salu2
Jul 23 '05 #7

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

Similar topics

30
13719
by: franky.backeljauw | last post by:
Hello, I am wondering which of these two methods is the fastest: std::copy, which is included in the standard library, or a manually written pointer copy? Do any of you have any experience with this? I would think that the library function std::copy would perform optimally, as it is a library function, and therefore the writers of this function would know best how to optimize it ... but some tests seem to indicate that my pointer copy...
7
4300
by: R. Anbeeswaran | last post by:
Hi All, void main() { const int i = 20; int *p = const_cast<int*>(&i); *p = 40; cout <<"i="<< i <<"\t"<<"*p="<<*p<<"\n"; }
6
1624
by: AlesD | last post by:
Hello, I can't figure out how to build assignment operator for class which contains "type* const value". --- example --- class parent_t; class child_t {
20
2069
by: CoolPint | last post by:
While I was reading about const_cast, I got curious and wanted to know if I could modify a constant variable through a pointer which has been "const_cast"ed. Since the pointer would be pointing to the constant variable and if I changed the value through the pointer, the constant variable should have been modified. Well, that's what I thought until I wrote the following and run it. #include <iostream> using std::cout; using std::endl;
6
2139
by: Simon Bailey | last post by:
In the following code at the end of the program z = 20 & y = 99. void doit(const int* x) { int* nonconst; nonconst = const_cast<int*>(x); *nonconst = 99; } int main(int argc, char* argv)
5
2383
by: wkaras | last post by:
I've compiled this code: const int x0 = 10; const int x1 = 20; const int x2 = 30; int x = { x2, x0, x1 }; struct Y {
5
9190
by: Tom Smith | last post by:
I hardly dare ask this given the furore in another thread over strings and const... My problem is this. I am assured that casting away the constness of the return value of std::string::c_str() is an Error according to the Standard. But I need to pass it to a function (in an old and unpleasant C library, ugh) which takes an ordinary char*. What should I do? Is it really necessary to make a fresh copy of the string? (I'm not asking this...
11
5022
by: Squeamizh | last post by:
class my_class { public: my_class() : value(0) { } int& get_value() { return value; } const int& get_value() const { my_class& c = const_cast<my_class&>(*this); return c.get_value(); }
2
3177
by: puru | last post by:
I have a template class like below. template <TInt Sclass XYZ { } const XYZ<10abc; //Instance of the class How do remove the constantness of abc using const_cast. I mean, I want the syntax for that. Something like const_cast<XYZ<10>abc gives
0
8095
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8588
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
8556
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
7030
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6068
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5526
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
4037
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...
1
2541
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
0
1407
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.