473,721 Members | 2,234 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

const_cast, reinterpret_cas t

Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?

2.) reinterpret_cas t.
I have used this a little when I converted a primitive to a class, but
would like to see other applications.

Yes, I have looked on the web, but want to know what some of the experts
know about this.

Thanks alot for your help,

John
Jul 22 '05 #1
18 4842
johny smith wrote:

Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?


I've had need to use this to cast away constness when interfacing w/ poorly
written interfaces that treat a parameter as const, but don't qualify it as
const in the parameter list.
Jul 22 '05 #2
"johny smith" <pr************ **@charter.net> wrote in message
news:10******** *****@corp.supe rnews.com...
Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?
It's for casting from const to non-const.
2.) reinterpret_cas t.
I have used this a little when I converted a primitive to a class, but
would like to see other applications.


You use it to convert between incompatible types, e.g.,
unsigned char buffer[20];
if(read_message _from_com_port( buffer))
{
double x = *reinterpret_ca st<double*>(buf fer);
//...
}

As a rule of thumb, use reinterpret_cas t if there is no implicit conversion
and static_cast is rejected by the compiler - and you are really sure that
it's the conversion you need.

If you are unable to find uses for these casts, then count your blessings.
No one _wants_ to use them. They should be used as little as possible, but
sometimes you have to use to use them.

DW

Jul 22 '05 #3
"johny smith" <pr************ **@charter.net> wrote in message
1.) const_cast
Don't know why you would do this?
If you implement the const function, you can implement the nonconst function
in terms of the nonconst one.

const T& Foo::stuff() const {
/* lots of code */
}

T& Foo::stuff() {
const Foo * cthis = this;
return const_cast<T&>( cthis->stuff);
}

Also, you need const_cast to add 2nd level const. Though this is rarely
used.

int main(int argc, char * * argv) {
char const *const * cargv = const_cast<char const *const *>(argv);
};

And you also need const_cast to deal with interfaces that aren't const
correct, for example using a variable as const by not declaring it const, as
Julie points out.
2.) reinterpret_cas t.
I have used this a little when I converted a primitive to a class, but
would like to see other applications.


One can use it to convert an int, double, etc to a stream of bytes, suitable
for a call to write.

int i = 3;
cout.write(rein terpret_cast<co nst char *>(&i), sizeof(i));

In pool allocator schemes, we allocate space to store N elements, say N =
100. You can treat the space of element as either an element or a pointer
to the next element, provided that the sizeof the space is >= the space of a
pointer to the element.

There are lots of other domain specific examples.
Jul 22 '05 #4
"David White" <no@email.provi ded> wrote in message
news:sL******** ***********@nas al.pacific.net. au...
"johny smith" <pr************ **@charter.net> wrote in message
news:10******** *****@corp.supe rnews.com...
Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?


It's for casting from const to non-const.


I guess now that you already knew that. I'm struggling to come up with
necessary uses for it, or uses that don't indicate a flawed design.
Stroustrup's "The C++ Programming Language" gives an example of a class
member used to cache a value. Even in a const member function you might want
to change the value of the cache, since the cache only affects performance
and not the logical state of the object. Changing a class member in a const
member function requires const_cast. However, I don't think this is a good
example because the member used as the cache would be better declared
'mutable', obviating the need for the const_cast. I did manage to find this
rather unsual case in my own code that uses both const_cast and
reinterpret_cas t:

class ParamDB
{
// A database class
};

// A handle used to access the database across a C interface
typedef struct DBHandleStruct_ {} *DBHandle;

DBHandle asDBHandle(cons t ParamDB *pDB)
{
return reinterpret_cas t<DBHandle>(con st_cast<ParamDB *>(pDB));
}

I suppose I could have (or should have) made DBHandle const struct
DBHandleStruct_ {} * and I still wouldn't have needed the const_cast.

DW

Jul 22 '05 #5

"David White" <no@email.provi ded> wrote in message
news:cx******** ***********@nas al.pacific.net. au...
"David White" <no@email.provi ded> wrote in message
news:sL******** ***********@nas al.pacific.net. au...
"johny smith" <pr************ **@charter.net> wrote in message
news:10******** *****@corp.supe rnews.com...
Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?


It's for casting from const to non-const.


I guess now that you already knew that. I'm struggling to come up with
necessary uses for it, or uses that don't indicate a flawed design.


Suppose you are writing an STL container class

class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIn tContainer*>(th is)->find(x);
}

...

const_cast avoids repeating a whole lot of code. (Possibly this indicates
the iterator/const_iterator concept in the STL is flawed design but there
you go).

john
Jul 22 '05 #6
John Harrison wrote:
David White wrote:
johny smith wrote:
Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?


It's for casting from const to non-const.

I guess now that you already knew that. I'm struggling to come up with
necessary uses for it, or uses that don't indicate a flawed design.


Suppose you are writing an STL container class

class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIn tContainer*>(th is)->find(x);
}

...

const_cast avoids repeating a whole lot of code. (Possibly this indicates
the iterator/const_iterator concept in the STL is flawed design but there
you go).


Or possibly that the first should be

iterator find (int x) const

Is there a particular reason this isn't the case?

--
Some say the Wired doesn't have political borders like the real world,
but there are far too many nonsense-spouting anarchists or idiots who
think that pranks are a revolution.

Jul 22 '05 #7

"Owen Jacobson" <an******@lions anctuary.net> wrote in message
news:pa******** *************** *****@lionsanct uary.net...
John Harrison wrote:
David White wrote:
johny smith wrote:
Can someone please give me some good reference site/information for
understanding when and why I would use

1.) const_cast
Don't know why you would do this?

It's for casting from const to non-const.

I guess now that you already knew that. I'm struggling to come up with
necessary uses for it, or uses that don't indicate a flawed design.


Suppose you are writing an STL container class

class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIn tContainer*>(th is)->find(x);
}

...

const_cast avoids repeating a whole lot of code. (Possibly this indicates the iterator/const_iterator concept in the STL is flawed design but there you go).


Or possibly that the first should be

iterator find (int x) const

Is there a particular reason this isn't the case?


Yes its by design. If it we're not the case you would be able to write code
like this

const MyIntContainer c = ...;
iterator i = c.find(1);
*i = 2;

in other words you would be able to use an iterator to modify a const
object.

john
Jul 22 '05 #8
In article <o8************ ********@bgtnsc 04-news.ops.worldn et.att.net>,
"Siemel Naran" <Si*********@RE MOVE.att.net> wrote:
If you implement the const function, you can implement the nonconst function
in terms of the nonconst one.

const T& Foo::stuff() const {
/* lots of code */
}

T& Foo::stuff() {
const Foo * cthis = this;
return const_cast<T&>( cthis->stuff);
}


Is there a clean (without a cast) way to do this, implementing the
non-const version first ?
Jul 22 '05 #9
On Thu, 24 Jun 2004 07:19:28 GMT, Owen Jacobson
<an******@lions anctuary.net> wrote:
Or possibly that the first should be

iterator find (int x) const

Is there a particular reason this isn't the case?


Since you could then modify a const container. e.g.

*myconstlist.fi nd(0) = 10;

Tom
--
C++ FAQ: http://www.parashift.com/c++-faq-lite/
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
Jul 22 '05 #10

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

Similar topics

4
2804
by: S.Senthilvel | last post by:
hi, I am a little confused about the const_cast.I've thought it this way till now. //Proper cast int i = 10; const int* pci = &i; int *pi = const_cast<int*>(pci);
11
5147
by: Scott Brady Drummonds | last post by:
Hi, everyone, I've checked a couple of on-line resources and am unable to determine how reinterpret_cast<> is different from static_cast<>. They both seem to perform a compile-time casting of one type to another. However, I'm certain that there is something else that is happening. Can someone explain the difference or recommend an online site that can explain it to me?
6
2144
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)
11
3794
by: Someonekicked | last post by:
I want to save tables of integers to files. One way to write the cells as fixed size in the file, is to use reinterpret_cast. Is that a bad choice, good choice? I remember once before I posted a program using it, and some suggested that I might get errors using it. are there any other ways to write the cells as fixed size in the file? (knowing the cells will only contain integers). here is how I plan to do it (without much caring...
7
10908
by: Peter | last post by:
I never used reinterpret_cast -- probably because I don't know what it means. Can somebody enlighten me? I looked into Stroustrup's "The annoted C++ reference manual" -- but this was no help. Can I assume that reinterpret_cast is not safe and should not be used? Does it always succeed even if the cast is garbage?
12
1771
by: ralpe | last post by:
Hi, I have a template class foo which stores pairs of Keys and Ts in a vector. Foo has an accessor function at(size_t) that returns a reference to the pair at the specified index. I do not want the users of foo to change the first value of a pair, so I want to return a reference to a pair<const Key, T>, just like std::map does. I cannot store pairs with a const first value in the vector because such pairs would not be assignable.
2
2959
by: jasm | last post by:
hello everybody! I have used reinterpret_cast for interpret a class object as a char*. This is the object: template<class T> class Coordinates { public: T *x; T *y;
4
2468
by: subramanian100in | last post by:
when are the use of static_cast and const_cast essential ? Stroustrup, in his book TC++PL(3rd edition) in page number 139 (in Section 6.5 Advice - ), has advised "Avoid explicit type conversion(casts)" Given this, why do we have static_cast and const_cast provided by the language ? Kindly explain
2
2679
by: ciccio | last post by:
Hi, I was wondering what the main reason is why reinterpret_cast fails to work as expected when using optimizations. Here is the simple example code which fail to give the correct result when optimizing. #include <iostream> int main() { long D1 = 0xbcfbc4f0d9b65179; long D2 = 0xbcfbc4f0d9b65042;
0
8840
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
8730
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
9367
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
9215
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
8007
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
6669
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
5981
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
4753
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2576
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.