开发者

C++ casting question (structs)

开发者 https://www.devze.com 2023-02-04 00:08 出处:网络
In my C++ application I have the definition: struct socksddr_storage ss; struct sockaddr *sa; what is the different between the following:

In my C++ application I have the definition:

struct socksddr_storage ss;
struct sockaddr *sa;

what is the different between the following:

sa = (struct sockaddr *)&ss; 

and

sa = (sockaddr *)&ss;

???

开发者_运维技巧Any help?


There is no difference between the two. The typecast with the struct keyword present harkens back to the days of C, where the type of a struct included the keyword "struct" and is why the phrase "typedef struct" became popular. C++ eliminated the need for this keyword in this context, but kept the syntax alive for backward compatibility.


There is no difference in C++ as the struct keyword is optional. In C, the second form is not legal.


The difference is that (struct sockaddr*) is a valid cast in both C and C++, where is (sockaddr*) is valid in C++ but not in C. Both casts achieve the same result.


As others already said, you don't need to write the struct prefix in c++ as the compiler is able to determine the correct type by the name only. But I suggest to use reinterpret_cast in this situation, as the c style cast is the big-hammer cast which casts types and const specifiers in one go.

struct socksddr_storage ss;
const struct socksddr_storage ss2;
struct sockaddr *sa;

sa = reinterpret_cast<sockaddr *>(&ss); // Works like the C Cast
sa = reinterpret_cast<sockaddr *>(&ss2); // Fails, because ss2 is a constant,
 // but sa is a pointer to a no const memory location. The C cast will allow
 // this assignment, but this can lead to runtime errors since the linker
 // can place ss2 into read-only memory.


I cannot say definite thing as I don't know your actual context, but if you see an error when you write (sockaddr*) and don't when (struct sockaddr*), my answer may apply. struct sockaddr in (struct sockaddr*) is an elaborated type specifier. Sometimes this is needed. For example,

void f( void* p )
{
  int stat( char const*, struct stat* );
  struct stat *a = (struct stat*) p; // cannot omit this struct
}
0

精彩评论

暂无评论...
验证码 换一张
取 消