Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

const_cast does not work to remove constness in argument

bilderbikkelbilderbikkel Posts: 754Member
Dear fellow PH-users,

When using std::seach_n in a const-correct way I ran into problems. I found a workaround, but I hope one of you can give an in-depth explanation.

The following code should compile, but it doesn't (under the IDE C++ Builder 6.0 Enterprise edition with the Borland compiler BCB.exe version 6.0.10.157):

[code]
const std::string s = "abc***def";
const int n = 3; //Number of repeats
std::search_n( s.begin(),s.end(),n,'*');
[/code]

The compile-error given is 'Cannot modify const object', because 'n' is of type 'const int'. Although the real problem is in the std::search_n algorithm, I use the following workaround:

[code]
const std::string s = "abc***def";
const int n = 3; //Number of repeats
std::search_n( s.begin(),s.end(),static_cast(n),'*');
[/code]

Due to the static_cast to integer type, this compiles nicely. But what I also tried is to const_cast the const integer n to integer type, as below:

[code]
const std::string s = "abc***def";
const int n = 3; //Number of repeats
std::search_n( s.begin(),s.end(),const_cast(n),'*');
[/code]

This again gives the compile-error 'Cannot modify const object'.

IMHO the const_cast is better then the static_cast (because I want the constness away).

So my question is: why does static_cast work and why doesn't const_cast work?

Thanks in advance, Bilderbikkel

Comments

  • bilderbikkelbilderbikkel Posts: 754Member
    Answer by Sergey (thanks!):

    As section 5.2.11 Const cast [expr.const.cast] of ISO C++ standard suggests, there are limited amount of conversion that can be performed using const_cast, so const_cast operator can be briefly described as applicable to two pointers to the same type with various cv-qualifiers. So point is that you can't const_cast to any type other that pointer or reference.

    And static_cast worked becouse it created new temporary object from existing one, it is was similar to use "const int n = 10; search_n( s.begin(), s.end(), int( n), '*');". But I suppose that these casts are redundant becouse arguments are passed by value so algorithm don't affects "outer" variables.
Sign In or Register to comment.