Des1gnWizard
Des1gnWizard

Reputation: 497

Is this casting away const?

const char cp[]="jkasdkasjsad";
string a=static_cast<string>(cp);//"const string a" also runs without any error

I have stuck at the above code for the whole afternoon. C++ Primer only give a code like

const char cp[]="jkasdkasjsad";
static_cast<string>(cp);

Could someone tell me is my code legal? Could I call it "cast away const" since no "const" before "string a"?

Any well-defined type conversion, other than those involving low-level const, can be requested using a static_cast. For example, we can force our expression to use floating-point division by casting one of the operands to double:

I was confused about the description above, what does "those involing low-level const" mean? Involving at left side or right side of an assignment? Anyone can save me.. Many thanks!

Upvotes: 1

Views: 460

Answers (3)

αλεχολυτ
αλεχολυτ

Reputation: 5039

Your code is perfectly legal according to the clause 5.2.9/4 of C++ standard:

An expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.

For your example T is std::string, e is cp. There is no casting away constness because of new object creation. Compare with this:

char* p = static_cast<char*>(cp); // error

Upvotes: 1

ForEveR
ForEveR

Reputation: 55887

There is no real casting at all in this case.

static_cast<string>(cp);

is equivalent to call to string constructor

string(cp);

Temporary variable of type string constructed from cp will be returned from static_cast. Since, I think we talk about std::string, than this constructor will be called

basic_string( const CharT* s,
              const Allocator& alloc = Allocator() );

Constructs the string with the contents initialized with a copy of the null-terminated character string pointed to by s. The length of the string is determined by the first null character.

Upvotes: 2

marcinj
marcinj

Reputation: 49986

Your string from cp array is being copied, string variable is not const

const char cp[] = "jkasdkasjsad";
std::string a = static_cast<std::string>(cp);

is equivalent to:

std::string ab = cp;

cp decays to pointer to first element of cp array

Upvotes: 2

Related Questions