473,796 Members | 2,916 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

static_cast vs reinterpert_cas t

Hi,

I have a
class A : public B {...member functions...... data members};

and am doing the following
A *p=new A();
void *p=static_cast< void *>(p);
factory_instanc e->process(p);

Here p is passed to a function, which accepts void ptr. That function
need to cast it back
A *pp=static_cast <A *>(p);

The function is in the factory which accepts void *p only, the specific
implementations need to cast the pointer back to the expected class
and use it.

Question:Though both works fine, yet I want to know what is more
appropriate in this situation static_cast OR reinterpert_cas t

The books suggests
static_cast= "For "well-behaved" and "reasonably
well-behaved" casts,including things you might now do without a cast
reinterpret_cas t=To cast to a completely different meaning. The key
is that you'll need to cast back to the original type to use it
safely.

But I am not able to interpret the sentences in this context :-)

Jul 10 '06
24 4769
Frederick Gotham wrote:
dio posted:

>>Frederick Gotham <fg*******@SPAM .comwrote:
>>>The major drawback of the new-style casts is that they take up far too
much horizontal screen space.

Yes, which should serve as a visual reminder that a design that relies
heavily on casts is perhaps not ideal.

I'm out of nappies now though, and I can judge sensibly as to when I should
use what kind of cast. Would you prefer:

int *p = reinterpret_cas t<int*>(
const_cast<char *>(pcc)
);

or:

int *p = (char*)pcc;

Very much the former. The horrible code emphasises the horrible action!
And,
size_t i = static_cast<siz e_t>(-1);

or:

size_t i = (size_t)-1;
The former.

--
Ian Collins.
Jul 11 '06 #11

"Frederick Gotham" <fg*******@SPAM .comwrote in message
news:fO******** ***********@new s.indigo.ie...
dio posted:
>Frederick Gotham <fg*******@SPAM .comwrote:
>>The major drawback of the new-style casts is that they take up far too
much horizontal screen space.

Yes, which should serve as a visual reminder that a design that relies
heavily on casts is perhaps not ideal.


I'm out of nappies now though, and I can judge sensibly as to when I
should
use what kind of cast. Would you prefer:

int *p = reinterpret_cas t<int*>(
const_cast<char *>(pcc)
);
This one. It spells out exactly what is going on.
>
or:

int *p = (char*)pcc;
And,
size_t i = static_cast<siz e_t>(-1);
This one.
or:

size_t i = (size_t)-1;
(Second example is intended to supress a compiler warning)
--

Frederick Gotham

Jul 12 '06 #12
Frederick Gotham wrote:
Victor Bazarov posted:
>Frederick Gotham wrote:
>>I have a simple rule-of-thumb:

If you can use static_cast, then use static_cast.

If you can't use static_cast, then use reinterpret_cas t.

I have a simple preceding rule:

If you can do it without a cast, do not use any cast.

Naturally ; )
I tend to use the old-style casts now and again too, e.g.:

enum { len = 64U };

int array[len];

for(size_t i = len - 1; (size_t)-1 != i; --i)
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)

But I think that's just because C style casts look so old-style to me
now ;-)
Or if I need a reinterpret_cas t and a const_cast at the same time:

char const *pc = 0;

int *pi = (int*)pc;

/* A very contrived example, I realise! */
That's an example of a situation where I would definitely go with the C++
style casts. One important advantage is that someone reading the code will
immediately see that I really intended to cast away the constness and
didn't just get it in by accident.

Jul 13 '06 #13
Rolf Magnus wrote:
>
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)

But I think that's just because C style casts look so old-style to me
now ;-)
But a single arg function-style cast is identical in meaning to the
C-style cast. You're back to it possibly meaning static, const,
reinterpret or combinations of the above (as well as busting access
control which there is no C++-style equivelent to).
Jul 13 '06 #14
Ron Natalie wrote:
Rolf Magnus wrote:
>>
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)

But I think that's just because C style casts look so old-style to me
now ;-)

But a single arg function-style cast is identical in meaning to the
C-style cast. You're back to it possibly meaning static, const,
reinterpret or combinations of the above (as well as busting access
control which there is no C++-style equivelent to).
I know. As I wrote, it's just that the C style cast looks more C'is than the
constructor style. Also note that none of the things you mentioned are an
issue in the above code example.

Jul 13 '06 #15
"Ron Natalie" <ro*@spamcop.ne twrote in message
news:44******** *************** @news.newshosti ng.com...
Rolf Magnus wrote:
>>
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)

But I think that's just because C style casts look so old-style to me
now ;-)

But a single arg function-style cast is identical in meaning to the
C-style cast. You're back to it possibly meaning static, const,
reinterpret or combinations of the above (as well as busting access
control which there is no C++-style equivelent to).
Actually, not at all. size_t(-1) tells me exactly what is going on. This
is a size_t variable that is being initialized to -1. There is no ambiguity
at all. It is not techinically a cast, I don't think.
Jul 13 '06 #16
Jim Langston wrote:
"Ron Natalie" <ro*@spamcop.ne twrote in message
news:44******** *************** @news.newshosti ng.com...
>Rolf Magnus wrote:
>>>
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)

But I think that's just because C style casts look so old-style to me
now ;-)

But a single arg function-style cast is identical in meaning to the
C-style cast. You're back to it possibly meaning static, const,
reinterpret or combinations of the above (as well as busting access
control which there is no C++-style equivelent to).

Actually, not at all. size_t(-1) tells me exactly what is going on. This
is a size_t variable that is being initialized to -1. There is no
ambiguity at all. It is not techinically a cast, I don't think.
size_t is unsigned and can't have negative values. size_t(-1) tells the
compiler that you want -1 converted to size_t, IOW, it's a cast.

Jul 13 '06 #17
In message <e9************ *@news.t-online.com>, Rolf Magnus
<ra******@t-online.dewrites
>
I tend to use constructor-style casts in such a situation:

for(size_t i = len - 1; size_t(-1) != i; --i)
I'd lose the -1 altogether ;-)

for (size_t i = len; i-- != 0; )
--
Richard Herring
Jul 13 '06 #18
Richard Herring posted:
> for(size_t i = len - 1; size_t(-1) != i; --i)

I'd lose the -1 altogether ;-)

for (size_t i = len; i-- != 0; )

Yes but this has re-arranged the natural order of the loop.

I like my "for" loops to have four phases:

(1) The "initialisa tion stuff" is executed first of all.

(2) The condition is tested.

(3) The body is executed.

(4) The "prepare for next iteration" stuff is executed.
Your example mixes (2) and (4), which I don't like.

--

Frederick Gotham
Jul 13 '06 #19
Rolf Magnus posted:

size_t is unsigned and can't have negative values. size_t(-1) tells the
compiler that you want -1 converted to size_t, IOW, it's a cast.

There's an implicit conversion from int to size_t, so no cast is required.

When dealing with intrinsic types, the following are exactly equivalent:

short(5)

(short)5

I myself prefer the latter, for two reasons:

(1) You can have types which consist of more than one word, e.g.
"unsigned short".
(2) It resembles a cast.

I dislike the former because:

(1) It looks like the construction of a user-defined class type.
(2) It doesn't resemble a cast at all.
(3) You can't use types which consist of more than one word.
--

Frederick Gotham
Jul 13 '06 #20

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

Similar topics

7
6367
by: Gary Labowitz | last post by:
Am I doing this correctly? It is a sample program for my class. #include <iostream> using namespace std; int main( ) { int x=3, y=4;
11
5155
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?
9
4175
by: news.ir.com.au | last post by:
Hi, In the following code I get the compiler error: error C2243: 'static_cast' : conversion from 'class B *' to 'class A *' exists, but is inaccessible I understand why I get this error and can usually get around the situation by inserting a "using A::..." statement inside class B, however, due to this being a static cast, what is the syntax?
26
2559
by: Steven T. Hatton | last post by:
The code shown below is an example from the Coin3D documentation. I believe the use of the C-style cast is safe under the circumstances, but from what I've been exposed to (TC++PL(SE)), I would favor using a static_cast. Is there any technical reason to favor the C-style over a static_cast? http://doc.coin3d.org/Coin/index.html void foo(SoNode * node) { if (node->getTypeId() == SoFile::getClassTypeId()) {
3
1930
by: shrishjain | last post by:
Hi All, Do people frequently use static_cast, const_cast etc in industry?.. I only saw them in books, and never in real code.. Shrish
2
1961
by: Amit | last post by:
Greetings. I am having some problem while using a cast operation(static_cast and/or dynamic_cast) between base and derived objects when passing to functions. what I have is something like this.. template <class T> class Node{ protected: T e; Node* left;
19
3764
by: PengYu.UT | last post by:
I see some code use static_cast<some_pointer_type>(0) instead of NULL to describe null pointer. I'm wondering what is the pros and cons of each way. Is there any reason why we should one verses the other.
5
3915
by: jason.cipriani | last post by:
There have been some recent threads about casting pointers to and from void* that have me rethinking some of my usual practices. I have a couple of questions. 1. What is the purpose of C++'s static_cast<>? In other words, is there any real difference between statements like (with non-pointer types): double a = 3.4; int b = (int)a; // <--- this
3
367
by: Rahul | last post by:
Hi, Everywhere I read that static_cast<only work fine for the conversion which are implicitly allowed by the compiler hence the following does not work int *i; double *d; d = i; // Compilation error , OK i= static_cast<int *>(d); // Compilation error. OK
0
9536
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
10468
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...
1
10205
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10021
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
9063
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
7559
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
5582
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4131
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
3748
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.