gpt4 book ai didi

c++ - 当在 Objective-C++ 中应用于 __weak 指针时,通过 "auto"关键字推导类型的规则是什么?

转载 作者:搜寻专家 更新时间:2023-10-31 02:10:47 26 4
gpt4 key购买 nike

假设我有一个 Objective-C 类 Foo:

@interface Foo: NSObject
@end
@implementation Foo
@end

然后在 Objective-C++ 文件 (.mm) 中,我有以下代码:

Foo *strongFoo = [Foo new];
__weak Foo* weakFoo = strongFoo;

auto foo = weakFoo; // ???

包含“???”的行中的变量 foo 的类型是什么? ?它是指向 Foo 的强指针还是弱指针?这是在某些标准和/或文档中的某处定义的吗?谢谢。

最佳答案

我根据一个规律来做一个总结:
1. Objective-C++ 不改变 C++ 的规则并返回。

auto然后作品不同typeof声明。 auto works类似的模板。

Once the type of the initialiser has been determined, the compiler determines the type that will replace the keyword auto using the rules for template argument deduction from a function call

在 clang 文档中,您可以找到 Ownership Qualification 的描述在 Template arguments部分,你可以阅读:

If a template argument for a template type parameter is an retainable object owner type that does not have an explicit ownership qualifier, it is adjusted to have __strong qualification. This adjustment occurs regardless of whether the template argument was deduced or explicitly specified.

description 中有很好的例子的 auto确定变量类型的模板函数:

For example, given const auto& i = expr;, the type of i is exactly the type of the argument u in an imaginary template template<class U> void
f(const U& u)
if the function call f(expr) was compiled.

如您所见,未声明 const U& 的所有权资格。因此U是对 Foo 的强烈引用.
在你的例子中 auto foo = weakFoo;将转换为 template<const (Foo*)> f(const Foo*& u) .如您所见, Foo* 是对 Foo 实例的强引用。

关于c++ - 当在 Objective-C++ 中应用于 __weak 指针时,通过 "auto"关键字推导类型的规则是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44690475/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com