我有这个示例代码:
const NSMutableString *const foobar = [[NSMutableString alloc] initWithFormat:@"Hello"]; [foobar appendString:@" World"]; NSLog(@"String: %@", foobar);它输出:
字符串:Hello World
我的变量不应该是const (以及指针)吗? 因此我不能修改它。
C ++的行为与我期望的一样
int main() { const std::string *const s = new std::string("hello"); s->append(" world"); std::cout << s << std::endl; }输出:
$ g++ test.c++ test.c++: In function ‘int main()’: test.c++:7:20: error: passing ‘const 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");我知道我不应该使用const和mutable,但这并没有改变事实,即mutable应该是const 。
I have this sample code:
const NSMutableString *const foobar = [[NSMutableString alloc] initWithFormat:@"Hello"]; [foobar appendString:@" World"]; NSLog(@"String: %@", foobar);and it outputs:
String: Hello World
Shouldn't my variable be const (as well as the pointer)? Therefore I should not be able to 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 function ‘int main()’: test.c++:7:20: error: passing ‘const 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 I shouldn't use const with mutable, but that doesn't change the fact, that the mutable should be const.
最满意答案
您的观察是正确的,在T是Objective-C类的情况下, 指向 常量T的类型指针会自动更改为指向T的指针 。
这在技术上不是偏离C(++)中const的语义,因为C(++)中没有Objective-C类类型,因此它们不被C(++)标准所涵盖。
Objective-C本身没有任何形式的描述,足够标准。 Objective-C 2.0编程语言 ,2009,没有提到常量语义,也很久以来作为参考被遗弃并且没有被替换。
换句话说,我无法指引您使用任何明确的文档,该文档声明const默默地省略了Objective-C类类型,但这就是编译器的行为方式。
如果你想要“常量”对象,你必须遵循Objective-C可变/不可变类模式。
Your observation is correct, the type pointer to a constant T is silently changed to pointer to a T in the cases where T is an Objective-C class.
This isn't technically a deviation from the semantics of const in C(++) as there are no Objective-C class types in C(++) and they are therefore not covered by the C(++) Standards.
Objective-C itself is not defined by any formal description, well enough a Standard. The Objective-C 2.0 Programming Language, 2009, makes no mention of constant semantics, and is also long since abandoned as a reference and has not been replaced.
In other words I cannot direct you to any definitive document that states that const is silently elided for Objective-C class types, but that is how the compilers behave.
If you want "constant" objects you have to follow the Objective-C mutable/immutable class pattern.
更多推荐
发布评论