1

Possible Duplicate:
behaviour of const_cast

I need to understand what this line means

char A = strdup(const_cast<char*>(aString.c_str()));

I understand what strdup does from this:

strdup() - what does it do in C?

strdup expects a const char pointer. Its the <,> part of the above line that confuses me.

Community
  • 1
  • 1
nulltorpedo
  • 1,195
  • 2
  • 12
  • 21

3 Answers3

3

const_cast< type > is a C++ operator. You can read about it here.

I don't understand why it's needed here, since (assuming aString is of type std::string) c_str() already returns the const char* which strdup requires, and in any case adding constness is done implicitly.

Only if the function receives a non-const parameter it's required, and even then it's usually not recommended.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
Asaf
  • 4,317
  • 28
  • 48
1

The cast operator,

char * p = const_cast<char*>(q);

allows you to remove the constness (provided that q is a const char *).

In general const_cast<T> can be used to add or remove the const qualifier.

However, as strdup should be taking a const char * the cast here is not needed.

1
                         aString

A variable, probably of type std::string

                         aString.c_str()

A const char * which points to nul-terminated array of chars

       const_cast<char*>(aString.c_str())

A cast, converting the value that is inside () to the type named inside <>. In this case, converting from const char* to char*. This is a C++-style cast (see also static_cast<>(), dynamic_cast<>(), and reinterpret_cast<>()).

strdup(const_cast<char*>(aString.c_str()));

As you say, you know what strdup does. Since the signature of strdup is probably char* strdup(const char*), it turns out that this particular cast is pointless.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308