Why can I change this constant NSMutableSring?

I have this code example:

const NSMutableString *const foobar = [[NSMutableString alloc] initWithFormat:@"Hello"];
[foobar appendString:@" World"];
NSLog(@"String: %@", foobar);

and outputs:

String: Hello World

Should my variable be const(as well as a pointer)? Therefore, I could not modify it.

C ++ behaves the way I expect

int main() {
    const std::string *const s = new std::string("hello");
    s->append(" world");
    std::cout << s << std::endl;
}

output:

$ g++ test.c++
test.c++: In functionint main()’:
test.c++:7:20: error: passingconst string {aka const std::basic_string<char>}’ as ‘this’ argument of ‘std::basic_string<_CharT, _Traits, _Alloc>& std::basic_string<_CharT, _Traits, _Alloc>::append(const _CharT*) [with _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’ discards qualifiers [-fpermissive]
  s->append(" world");

I know that I should not use constmutable, but that does not change the fact that mutable should be const.

+4
source share
3 answers

Your observation is correct, a type pointer to a constant T quietly changes to a pointer to T in cases where T is an Objective-C class.

const C (++), C (++) Objective-C, C (++) ) .

Objective-C - , . Objective-C 2.0, 2009, .

, - , , const Objective-C, .

"" , Objective-C mutable/immutable.

+2

, : "const NSMutableString * const foobar" : ptr . , , , .

++ , - , const, Objective-C , .

+2

constmeans the address of the pointer is constant, so you can change / add a line. Also best practice is always to use const c NSString. Hope this helps.

-1
source

Source: https://habr.com/ru/post/1534656/


All Articles