我有这个示例代码:
const NSMutableString *const foobar = [[NSMutableString alloc] initWithFormat:@"Hello"]; [foobar appendString:@" World"]; NSLog(@"String: %@",foobar);
它输出:
String: 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,_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.
解决方法
您的观察是正确的,在T是Objective-C类的情况下,指向常量T的类型指针会自动更改为指向T的指针.
这在技术上不是偏离C()中const的语义,因为C()中没有Objective-C类类型,因此它们不被C()标准所涵盖.
Objective-C本身并没有任何正式的描述,足够标准. Objective-C 2.0编程语言,2009,没有提到常量语义,也很久以来作为参考被遗弃并且没有被替换.
换句话说,我无法指引您查看任何明确的文档,该文档声明const默默地省略了Objective-C类类型,但这就是编译器的行为方式.
如果你想要“常量”对象,你必须遵循Objective-C可变/不可变类模式.