c++ - C++中 "const reference"的概念在Objective-C中是否存在

标签 c++ objective-c reference constants

我担心引用,当我在 Objective-C 中调用方法时,我会避免对象的最大拷贝。

有人说Objective-C是按值传递对象,那么这个C++在Objective-C中还有可能吗?或者是否存在解决方法?

目前我看到的唯一解决方案是使用 Objective-C++。

最佳答案

在 Objective-C 中,所有对象都是在堆上创建的。因此所有对象都被引用。因此,没有对象被“静静地”复制,尤其是在传递给方法或函数时:

NSString *foo = @"bar"; // foo is a reference to a string object
doSomething( foo ); // a reference is passed

Objective-C 总是像 C 一样按值传递参数,但是因为它总是一个引用,所以引用被复制(通常是一个机器字)而不触及被引用对象的身份。

void doSomething( NSMutableString* foo ) // A function taking a reference to an instance of NSMutableString
{
  [foo appendString:@"foobar"];
  foo = nil;
}

NSMutableString *foo = [@"bar" mutableCopy]; // foo is a reference to an instance of NSMutableString
doSomething( foo ); // A copy of the reference, nor the object neither a copy of the object is passed
// foo is unchanged, since it is copied through pass by value.
// the object, foo points to, is @"barfoobar", since the object is not copied

所以没有什么可以避免的。

关于c++ - C++中 "const reference"的概念在Objective-C中是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761611/

相关文章:

ios - 为什么 Xcode 在使用 @selector 时不提示未声明的方法?

ios - 当#define一个变量时,@interface @实现和.h有什么不同

c++ - 何时使用引用与指针

c++ - std::move 返回和输入引用参数

objective-c - Clang 和 gcc 选项可以抑制未定义的消息警告?

c++ - 如何创建 Eigen::Ref vector

c++ - syscalls.h 以及 minor() 和 major() 函数

c++ - 使用 cmake 将 Eigen 库添加到 C++ 项目

c++ - 使用计数器模式用 SHA256 加密数据是否聪明?

android - 在android上编译需要STL的库