【问题标题】:Does the concept of "const reference" in C++ exists in Objective-CObjective-C中是否存在C++中“const引用”的概念
【发布时间】:2017-03-13 10:41:43
【问题描述】:

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

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

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

【问题讨论】:

  • 仅供参考,C++ 也通过值传递所有对象。传递引用时,传递引用的值。
  • @RichardCritten 并非如此,引用不是对象,因此严格来说,您不能复制它们或按值传递它们。
  • 我不知道 Objective-C 是否有对 const 的引用……但它肯定有 const 和指针。所以一个workround是指向const的指针。
  • @MartinBonner 在 Objective-C 中,对象的常量性不是由语言提供的,而是由类系统提供的。所以它只是引用一个常量类型的实例。
  • 可能。然而,没有人会关心那种类型的装饰,只需写-(void)myMethod:(MyType*)x。请注意,Objective-C 中没有方法调用,而是动态调度。这使得这种“优化”在 Objective-C 中毫无意义。长话短说:Objective-C 是一种完全不同的语言,因为它的类型系统完全不同。

标签: c++ objective-c reference constants


【解决方案1】:

在 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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 2012-12-07
    • 2016-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-22
    相关资源
    最近更新 更多