How to convert CStyle cast to c++, Unsigned Char to LPCSTR [duplicate] - c++

Why is my static_cast of a pointer failing?
int iDog = 456;
int *piDog = &iDog;
long *plDog = static_cast<long*>(piDog); // invalid type conversion
long lDog = static_cast<long>(iDog); // ok
long* plDog = (long*)(piDog); // this is OK too... very weird!! (Dynamic cast... and we aren't allowed to use this one in our coding standards)
This reference suggests it should be OK: https://en.cppreference.com/w/cpp/language/static_cast
Issue with Visual Studio C++?

long *plDog = static_cast<long*>(piDog); // invalid type conversion
Why is my static_cast of a pointer failing?
Because it is ill-formed. None of the rules of static_cast apply to the cast that you're attempting. It is an invalid conversion, as you mention in the comments.
A pointer to one object type may not be static casted to a pointer to another object type unless they are pointers to related classes, or when casting to/from pointer to void.
This reference suggests it should be OK: https://en.cppreference.com/w/cpp/language/static_cast
That reference suggests that the conversion you attempt is not OK.
long* plDog = (long*)(piDog); // this is OK too... very weird!!
This is a well-formed conversion. It's not "weird".
There are many conversions that explicit conversions (also called "cast notation" or "C-style cast") allow, and static casts do not allow. This is because static casts have (at least a semblance of) type safety while explicit conversions essentially ask the compiler to pretend that the type system doesn't exist.
Note that indirecting through plDog and accessing the object would result in undefined behaviour. As you can see, it was a good thing that you got the error.
and we aren't allowed to use this one in our coding standards
This is a good limitation to have. This will make it bit harder for your team to write bugs by mistakenly circumventing the type system.
Issue with Visual Studio C++?
No, the issue is that the program is ill-formed. The compiler is correct to inform you about the bug, and is not required to compile the program.
I recommend asking yourself: Why do you want to, or think that you need to do such cast?

TL;DR: If your cast worked, the language would provide no type-safety guarantees for pointers, and is a key part of the motivation for introducing the C++ style casts instead of sticking with the old-school C cast.
In the language of the C/C++ Standard, long* and int* are not "pointer-compatible". You can't implicitly convert a long* to an int* or vice-versa, so static_cast can't do it in a single cast.
The reasoning behind that is sizeof(long) is not always equal to sizeof(int) for all platforms. They are distinct fundamental types. This is true in general of all distinct C/C++ types even if they have an identical binary layout. They are only "pointer-compatible" if in the syntax of the language you declare the types to be related via implicit conversion.
You can use static_cast when converting from a void* to any pointer to an object type or vice-versa.
Therefore you can do this in two ways:
reinterpret_cast<long*>(piDog);
-or-
static_cast<long*>(static_cast<void*>(piDog));
Stylistically, the use of the reinterpret_cast is a lot clearer. In either case, the validity of the cast is architecture dependent and assumes sizeof(int) == sizeof(long) as well as having the same memory layout.
IOW This is safe for Windows x86 and x64 native, but may not hold for other platforms or CPUs. This is one of the reasons Windows x64 choose to use the LLP64 data model as explained in this blog post.
See cppreference for static_cast and reinterpret_cast

Related

Is it possible to auto cast (long *) to (int *)

I'm working on an existing code base, so the answer "do it right, just use one type" doesn't work because they already didn't do it right, I just have to live with it.
I know that coercion works so that this works:
int a = 1;
long b = a;
even though int and long are different base types. However, this doesn't work:
int a;
long *b = &a;
because there's no auto conversion between "pointer to int" and "pointer to long".
If, rather than base types, I was working with classes, I could get it to work by providing a conversion. My question is this. Is there a way to provide conversions for base types (or rather pointers to base types) so I could start the process of converting my code to use a single 32-bit integral type? As it stands, I either need to do an "all or nothing" edit OR provide a boatload of explicit casts.
My question is this. Is there a way to provide conversions for base types (or rather pointers to base types) so I could start the process of converting my code to use a single 32-bit integral type?
No, there is no way to influence the set of implicit conversions between pointer types aside from inheritance relations between classes.
Even if you add a (long*) cast or reinterpret_cast<long*> everywhere, as mentioned in the comments, accessing the value through that pointer will be an aliasing violation and therefore cause undefined behavior. This is not related to the size, alignment or the representation of the int and long types. Rather compilers are explicitly allowed to make optimizations that assume that a long pointer can never be pointing to a int object and compilers will perform such optimizations that will break code in possibly very subtle ways.
Note that this is different for casts between e.g. signed int* and unsigned int*. Signed and unsigned variants of the same integral type are allowed to alias one another, so that either pointer type can be used to access the object. The compiler is not allowed to perform optimizations in this case that assume that pointers of the two types don't point to the same address at the same time.
GCC and Clang offer the -fno-strict-aliasing option to disable optiizations based on the aliasing rules (still assuming that the type do actually have the same size, alignment and compatible representations), but I don't know whether MSVC has a similar option. Some compilers may also explicitly allow additional types to alias that the standard does not allow to alias, but I would only rely on that if the compiler documents these clearly. I don't know whether MSVC makes any such guarantees for int and long.

Is static_cast<int>(myUnsignedLongVar) implementation defined?

Common advice when writing C++ states that implicit conversions should be avoided in favour of explicit casts.
int x = myUnsignedLongVar; // should be avoided
while
int x = static_cast<int>(myUnsignedLongVar); // is preferred
Does a static_cast make this conversion any safer? As far as I'm aware both conversions are implementation defined?
Is the static_cast just a signal to indicate more verbosely that this operation is potentially implementation defined?
And who's implementation? Is the operation dependent on the implementation of the compiler or the CPU?
Both examples would produce the same code.
But, in the second one everyone knows that there’s a cast to int.
In the first one could assume myUnsignedLongVar is int.
In order to make sure nobody misses the cast, guidelines and compilers recommend making it explicit.
I believe your example is somewhat narrow to show the real difference between different types of casting.
If you are simply casting from unsigned int to int, or from double to int, this may not show its real value.
The real value comes when you do not want to allow casting to cause bugs in your program. For example when performing comparisons between signed and unsigned types, or pointer or changing object types. Moreover, C++ style casting i.e. static cast is checked by the compiler.
Another benefit is what you already mentioned. Verbosity. They ensure that the authors intent is captured.
Several answers to this question contain a nice summary and comparison between different types of casting.

C++ casting for C-style downcasting

When working with a C API that uses C-style inheritance, (taking advantage of the standard layout of C-structs), such as GLib, we usually use C-style casts to downcast:
struct base_object
{
int x;
int y;
int z;
};
struct derived_object
{
base_object base;
int foo;
int bar;
};
void func(base_object* b)
{
derived_object* d = (derived_object*) b; /* Downcast */
}
But if we're writing new C++ code that uses a C-API like this, should we continue to use C-style casts, or should we prefer C++ casts? If the latter, what type of C++ casts should we use to emulate C downcasting?
At first, I thought reinterpret_cast would be suitable:
derived_object* d = reinterpret_cast<derived_object*>(b);
However, I'm always wary of reinterpret_cast because the C++ standard guarantees very little about what will happen. It may be safer to use static_cast to void*:
derived_object* d = static_cast<derived_object*>(static_cast<void*>(b))
Of course, this is really cumbersome, making me think it's better to just use C-style casts in this case.
So what is the best practice here?
If you look at the specification for C-style casts in the C++ spec you'll find that cast notation is defined in terms of the other type conversion operators (dynamic_cast, static_cast, reinterpret_cast, const_cast), and in this case reinterpret_cast is used.
Additionally, reinterpret_cast gives more guarantees than is indicated by the answer you link to. The one you care about is:
§ 9.2/20: A pointer to a standard-layout struct object, suitably converted using a reinterpret_cast, points to its initial member (or if that member is a bit-field, then to the unit in which it resides) and vice versa.
If you want to use a cast notation I think using the C++ type conversion operators explicitly is best. However rather than littering casts all over the code you should probably write a function for each conversion (implemented using reinterpret_cast) and then use that.
derived_object *downcast_to_derived(base_object *b) {
return reinterpret_cast<derived_object*>(b);
}
However, I'm always wary of reinterpret_cast because the C++ standard
guarantees very little about what will happen.
C++-style casts are no less safe than C-style casts, because C-style cast is defined in terms of C++-style casts.
5.4.4 The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of explicit type conversion.
[...]
If a conversion can be interpreted in more than one of the ways listed above, the interpretation that
appears first in the list is used, even if a cast resulting from that interpretation is ill-formed.
The sad answer is that you can't avoid casts in code like you written, because the compiler knows very little about relations between classes. Some way or another, you may want to refactor it (casts or classes or the code that uses them).
The bottom line is:
If you can, use proper inheritance.
If you can't, use reinterpret_cast.
new C++ code that uses a C-API like this
Don't write new C++ code in a C style, it doesn't make use of the C++ language features, and it also forces the user of your wrapper to use this same "C" style. Instead, create a proper C++ class that wraps the C API interface details and hides them behind a C++ class.
should we continue to use C-style casts
No
or should we prefer C++ casts
Yes, but only when you have to.
Use C++ inheritance and virtual accessor functions (probably). Please show how you plan to use the derived object in func, this may provide a better answer for you.
If func expects to use the methods of the derived object, then it should receive a derived object. If it expects to use the methods of a base_object, but the methods are somehow changed because the pointer is to a derived_object, then virtual functions are the C++ way to do this.
Also, you want to pass a reference to func, not a pointer.
dynamic_cast, requires certain conditions to be met:
http://www.cplusplus.com/doc/tutorial/typecasting/
If you are just converting struct ptrs to struct ptrs and you know what you want, then static_cast, or reinterpret_cast may be the best?
However, if you truly are interested in writing C++ code, then the casts should be your last and final resort, since there are better patterns. The two common situations I would consider casting are:
You are interfacing with some event passing mechanism that passes a generic base class to an event handler.
You have a container of objects. The container requires it to contain homogenous types (i.e every element contains the same "thing"), but you want to store different types in the container.
I think dynamic_cast is exactly what you want.

Difference between static_cast<primitive_type>(foo) and primitive_type(foo) [duplicate]

I've heard that the static_cast function should be preferred to C-style or simple function-style casting. Is this true? Why?
The main reason is that classic C casts make no distinction between what we call static_cast<>(), reinterpret_cast<>(), const_cast<>(), and dynamic_cast<>(). These four things are completely different.
A static_cast<>() is usually safe. There is a valid conversion in the language, or an appropriate constructor that makes it possible. The only time it's a bit risky is when you cast down to an inherited class; you must make sure that the object is actually the descendant that you claim it is, by means external to the language (like a flag in the object). A dynamic_cast<>() is safe as long as the result is checked (pointer) or a possible exception is taken into account (reference).
A reinterpret_cast<>() (or a const_cast<>()) on the other hand is always dangerous. You tell the compiler: "trust me: I know this doesn't look like a foo (this looks as if it isn't mutable), but it is".
The first problem is that it's almost impossible to tell which one will occur in a C-style cast without looking at large and disperse pieces of code and knowing all the rules.
Let's assume these:
class CDerivedClass : public CMyBase {...};
class CMyOtherStuff {...} ;
CMyBase *pSomething; // filled somewhere
Now, these two are compiled the same way:
CDerivedClass *pMyObject;
pMyObject = static_cast<CDerivedClass*>(pSomething); // Safe; as long as we checked
pMyObject = (CDerivedClass*)(pSomething); // Same as static_cast<>
// Safe; as long as we checked
// but harder to read
However, let's see this almost identical code:
CMyOtherStuff *pOther;
pOther = static_cast<CMyOtherStuff*>(pSomething); // Compiler error: Can't convert
pOther = (CMyOtherStuff*)(pSomething); // No compiler error.
// Same as reinterpret_cast<>
// and it's wrong!!!
As you can see, there is no easy way to distinguish between the two situations without knowing a lot about all the classes involved.
The second problem is that the C-style casts are too hard to locate. In complex expressions it can be very hard to see C-style casts. It is virtually impossible to write an automated tool that needs to locate C-style casts (for example a search tool) without a full blown C++ compiler front-end. On the other hand, it's easy to search for "static_cast<" or "reinterpret_cast<".
pOther = reinterpret_cast<CMyOtherStuff*>(pSomething);
// No compiler error.
// but the presence of a reinterpret_cast<> is
// like a Siren with Red Flashing Lights in your code.
// The mere typing of it should cause you to feel VERY uncomfortable.
That means that, not only are C-style casts more dangerous, but it's a lot harder to find them all to make sure that they are correct.
One pragmatic tip: you can search easily for the static_cast keyword in your source code if you plan to tidy up the project.
In short:
static_cast<>() gives you a compile time checking ability, C-Style
cast doesn't.
static_cast<>() can be spotted easily
anywhere inside a C++ source code; in contrast, C_Style cast is harder to spot.
Intentions are conveyed much better using C++ casts.
More Explanation:
The static cast performs conversions between compatible types. It
is similar to the C-style cast, but is more restrictive. For example,
the C-style cast would allow an integer pointer to point to a char.
char c = 10; // 1 byte
int *p = (int*)&c; // 4 bytes
Since this results in a 4-byte pointer pointing to 1 byte of allocated
memory, writing to this pointer will either cause a run-time error or
will overwrite some adjacent memory.
*p = 5; // run-time error: stack corruption
In contrast to the C-style cast, the static cast will allow the
compiler to check that the pointer and pointee data types are
compatible, which allows the programmer to catch this incorrect
pointer assignment during compilation.
int *q = static_cast<int*>(&c); // compile-time error
Read more on:
What is the difference between static_cast<> and C style casting
and
Regular cast vs. static_cast vs. dynamic_cast
The question is bigger than just using whether static_cast<> or C-style casting because there are different things that happen when using C-style casts. The C++ casting operators are intended to make those different operations more explicit.
On the surface static_cast<> and C-style casts appear to be the same thing, for example when casting one value to another:
int i;
double d = (double)i; //C-style cast
double d2 = static_cast<double>( i ); //C++ cast
Both of those cast the integer value to a double. However when working with pointers things get more complicated. Some examples:
class A {};
class B : public A {};
A* a = new B;
B* b = (B*)a; //(1) what is this supposed to do?
char* c = (char*)new int( 5 ); //(2) that weird?
char* c1 = static_cast<char*>( new int( 5 ) ); //(3) compile time error
In this example (1) may be OK because the object pointed to by A is really an instance of B. But what if you don't know at that point in code what a actually points to?
(2) may be perfectly legal (you only want to look at one byte of the integer), but it could also be a mistake in which case an error would be nice, like (3).
The C++ casting operators are intended to expose these issues in the code by providing compile-time or run-time errors when possible.
So, for strict "value casting" you can use static_cast<>. If you want run-time polymorphic casting of pointers use dynamic_cast<>. If you really want to forget about types, you can use reintrepret_cast<>. And to just throw const out the window there is const_cast<>.
They just make the code more explicit so that it looks like you know what you were doing.
static_cast means that you can't accidentally const_cast or reinterpret_cast, which is a good thing.
Allows casts to be found easily in
your code using grep or similar
tools.
Makes it explicit what kind
of cast you are doing, and engaging
the compiler's help in enforcing it.
If you only want to cast away
const-ness, then you can use
const_cast, which will not allow you
to do other types of conversions.
Casts are inherently ugly -- you as
a programmer are overruling how the
compiler would ordinarily treat your
code. You are saying to the
compiler, "I know better than you."
That being the case, it makes sense
that performing a cast should be a
moderately painful thing to do, and
that they should stick out in your
code, since they are a likely source
of problems.
See Effective C++ Introduction
It's about how much type-safety you want to impose.
When you write (bar) foo (which is equivalent to reinterpret_cast<bar> foo if you haven't provided a type conversion operator) you are telling the compiler to ignore type safety, and just do as it's told.
When you write static_cast<bar> foo you are asking the compiler to at least check that the type conversion makes sense and, for integral types, to insert some conversion code.
EDIT 2014-02-26
I wrote this answer more than 5 years ago, and I got it wrong. (See comments.) But it still gets upvotes!
C Style casts are easy to miss in a block of code. C++ style casts are not only better practice; they offer a much greater degree of flexibility.
reinterpret_cast allows integral to pointer type conversions, however can be unsafe if misused.
static_cast offers good conversion for numeric types e.g. from as enums to ints or ints to floats or any data types you are confident of type. It does not perform any run time checks.
dynamic_cast on the other hand will perform these checks flagging any ambiguous assignments or conversions. It only works on pointers and references and incurs an overhead.
There are a couple of others but these are the main ones you will come across.
static_cast, aside from manipulating pointers to classes, can also be used to perform conversions explicitly defined in classes, as well as to perform standard conversions between fundamental types:
double d = 3.14159265;
int i = static_cast<int>(d);

What are the benefits of explicit type cast in C++?

What are the benefits of explicit type cast in C++ ?
They're more specific than the full general C-style casts. You don't give up quite as much type safety and the compiler can still double check some aspects of them for you.
They're easy to grep for if you want to try clean up your code.
The syntax intentionally mimics a templated function call. As a a result, you can "extend" the language by defining your own casts (e.g., Boost's lexical_cast).
Clarity in reading the code. There is not too much else of benefit, except for the cases where the compiler cannot infer the implicit cast at all, in which case you'd have to cast explicitly anyway.
The recommended way to cast in c++ is through dynamic_cast, static_cast, and the rest of those casting operators:
http://www.cplusplus.com/doc/tutorial/typecasting/
Notice that all typecasts are explicit in C++ and C. There are, in the language, no "implicit" typecasts. It's called "implicit conversions" and "explicit conversions", the latter of which are also called "casts".
Typecasts are most often used to inhibit warnings by the compiler. For instance if you have a signed and an unsigned value and compare them, the compiler usually warns you. If you know the comparison is correct, you can cast the operands to a signed type.
Another example is overload resolution, where type casts can be used to drive to the function to be called. For example to print out the address of a char, you can't just say cout << &c because that would try to interpret it as a C-Style String. Instead you would have to cast to void* before you print.
Often implicit conversions are superior to casts. Boost provides boost::implicit_cast to go by implicit conversions. For example the following relies on the implicit conversions of pointers to void*
cout << boost::implicit_cast<void*>(&c);
This has the benefit that it's only allowing conversions that are safe to do. Downcasts are not permitted, for example.
often used on void* to recover a implicitly known type. Especially common on embedded OS's for callbacks. This is a case where when you register for an event and maybe pass your "this" pointer as a context void*, then when the triggers it will pass you the void * context and you covert it back to the type the "this" pointer was.
Sometimes explicit casting avoids certain undesirable cirumstances by using explicit keyword.
class ExplicitExample
{
public:
ExplicitExample(int a){...}
}
ExplicitExample objExp = 'A';//No error.. call the integer constructor
Change as
explicit ExplicitExample(int a){ ... }
Now compile.
ExplicitExample objExp = 'A';
We get this error in VS2005.
error C2440: 'initializing' : cannot convert from 'char' to 'ExplicitExample'
Constructor for class 'ExplicitExample' is declared 'explicit'
To overcome this error, we have to declare as
ExplicitExample objExp = ExplicitExample('A');
It means as a programmer, we tell the compiler we know what we are calling. So compiler ignores this error.