473,406 Members | 2,343 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,406 software developers and data experts.

const_cast, reinterpret_cast

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_cast.
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 4804
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.supernews.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_cast.
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_cast<double*>(buffer);
//...
}

As a rule of thumb, use reinterpret_cast 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_cast.
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(reinterpret_cast<const 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.provided> wrote in message
news:sL*******************@nasal.pacific.net.au...
"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.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_cast:

class ParamDB
{
// A database class
};

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

DBHandle asDBHandle(const ParamDB *pDB)
{
return reinterpret_cast<DBHandle>(const_cast<ParamDB*>(pD B));
}

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.provided> wrote in message
news:cx*******************@nasal.pacific.net.au...
"David White" <no@email.provided> wrote in message
news:sL*******************@nasal.pacific.net.au...
"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.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<MyIntContainer*>(this)->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<MyIntContainer*>(this)->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******@lionsanctuary.net> wrote in message
news:pa****************************@lionsanctuary. 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<MyIntContainer*>(this)->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********************@bgtnsc04-news.ops.worldnet.att.net>,
"Siemel Naran" <Si*********@REMOVE.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******@lionsanctuary.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.find(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
"johny smith" <pr**************@charter.net> wrote in message
news:10*************@corp.supernews.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?

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


This is a very good article about reinterpret_cast:
http://msdn.microsoft.com/library/en...ep06012000.asp

Don't worry about the fact that it's on MSDN, it's not in the least
Microsoft specific. Robert Schmidt (the author) is a very standards-oriented
guy.
There's an article about static_cast too, but not about const_cast,
unfortunately.

--
Unforgiven

Jul 22 '05 #11
"John Harrison" <jo*************@hotmail.com> wrote in message
news:2jvbacF15ln3kU1@uni-
class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIntContainer*>(this)->find(x);
}


Coming to think of it, shouldn't you implement the const version, and
nonconst one in terms of the const one. Because the original object may
have been const. I didn't realize this until formulating my reply to Mats
Weber.
Jul 22 '05 #12
"Mats Weber" <ma***@bluewin.ch> wrote in message news:matsw-
"Siemel Naran" <Si*********@REMOVE.att.net> wrote:

If you implement the const function, you can implement the nonconst functionin 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 ?


No. In this second approach example you need a const_cast to cast away the
constness of this. So either way you need a const_cast.

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

The advantage of the first way I posted is that the original object may have
been declared const as in

int main() {
const Foo foo;
foo.stuff();
}

so it's not safe to cast away the constness of this. So we implement the
const version. The nonconst version will call the const version, then cast
away the constness of the returned reference or iterator or pointer -- which
should be OK because the original pointer, presumably a pointer to some part
of the object, was originally non-const.

Jul 22 '05 #13
"Unforgiven" <ja*******@hotmail.com> wrote in message
news:2jvvmsF13jrcmU1@uni-
This is a very good article about reinterpret_cast:
http://msdn.microsoft.com/library/en...ep06012000.asp


Good article!
Jul 22 '05 #14
Siemel Naran wrote in
news:3e********************@bgtnsc04-news.ops.worldnet.att.net in
comp.lang.c++:
"John Harrison" <jo*************@hotmail.com> wrote in message
news:2jvbacF15ln3kU1@uni-
class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIntContainer*>(this)->find(x);
}


Coming to think of it, shouldn't you implement the const version, and
nonconst one in terms of the const one. Because the original object
may have been const. I didn't realize this until formulating my reply
to Mats Weber.


Well should you be able to make an iterator from a const_iterator ?

Ofcourse calling the non-const find on a const object is fine as
long as we know that it doesen't modify the object, and in this
case why would it ?

Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #15
"Rob Williscroft" <rt*@freenet.co.uk> wrote in message
Ofcourse calling the non-const find on a const object is fine as
long as we know that it doesen't modify the object, and in this
case why would it ?


Note in the example we are returning an iterator to the caller. There's no
saying what they'll do with it.

Also, the standard says casting away the constness of an object that was
originally const, even if only for read purposes, is undefined. Maybe some
implementations out there have read only pointers builtin into the system, I
don't know. I suggested recently in a post that to get a "char *" from
string.c_str() you could practically do "const_cast<char*>(string. c_str())"
which would work on all implementations I know, but someone correctly
pointed out it is still undefined behavior if the original string were
const.
Jul 22 '05 #16
Siemel Naran wrote in
news:4N*********************@bgtnsc04-news.ops.worldnet.att.net in
comp.lang.c++:
"Rob Williscroft" <rt*@freenet.co.uk> wrote in message
Ofcourse calling the non-const find on a const object is fine as
long as we know that it doesen't modify the object, and in this
case why would it ?
Note in the example we are returning an iterator to the caller.
There's no saying what they'll do with it.


I was refering to the const_cast in the const member function,
and then calling the non-const find on it.
Also, the standard says casting away the constness of an object that
was originally const, even if only for read purposes, is undefined.
Do you have a reference ?
Maybe some implementations out there have read only pointers builtin
into the system, I don't know. I suggested recently in a post that to
get a "char *" from string.c_str() you could practically do
"const_cast<char*>(string. c_str())" which would work on all
implementations I know, but someone correctly pointed out it is still
undefined behavior if the original string were const.


Its UB anyway, we've no idea where the char const * returned by
c_str() comes from.
Rob.
--
http://www.victim-prime.dsl.pipex.com/
Jul 22 '05 #17
>> class MyIntContainer
{
iterator find(int x)
{
// some complex function
}

const_iterator find(int x) const
{
return const_cast<MyIntContainer*>(this)->find(x);
}


Coming to think of it, shouldn't you implement the const version, and
nonconst one in terms of the const one. Because the original object may
have been const. I didn't realize this until formulating my reply to Mats
Weber.


In this case you probably can't implement the non-const version in terms of the
const version.

The return type of the const version is most likely not convertible to the
return type of the non-const version.

It seems reasonble that one shouldn't be able to convert a constant iterator
into a non-constant iterator.

The reverse of course is quite reasonable.
Jul 22 '05 #18
"David White" <no@email.provided> wrote:
"johny smith" <pr**************@charter.net> wrote
1.) const_cast
Don't know why you would do this?


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


Also for casting from non-const to const, and volatile to non-volatile,
and non-volatile to volatile, and any combinations of those.
For example:

void foo(const char **ptr);
char *x;

foo(const_cast<const char **>(&x));
Jul 22 '05 #19

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

Similar topics

4
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
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...
6
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
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...
7
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....
12
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...
2
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
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...
2
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...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
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
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...
0
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...
0
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,...

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.