了解 Objective-C++ __block 修饰符
我需要对 Objective-C 应用程序进行一些维护(更新它以使用新的 API),并且以前从未使用过该语言,我有点困惑。
我有一个 Objective-C++ 类,它实现了我的 API 中的接口,并且在块内使用它,但是每当在块内访问它时,它就会失败并出现访问冲突错误 (EXC_BAD_ACCESS)。
进一步的调查表明,没有调用相关对象的构造函数。它在包含范围内声明,并使用 __block 修饰符。
为了尝试理解这一点,我做了一个快速的临时应用程序,发现那里发生了同样的事情:
class Foo
{
public:
Foo() : value(1) { printf("constructor"); }
void addOne() { ++value; printf("value is %d", value); }
private:
int value;
};
void Bar()
{
Foo foo1; // prints "constructor"
__block Foo foo2; // doesn't print anything
foo1.addOne(); //prints "2"
foo2.addOne(); //prints "1"
}
任何人都可以解释这里发生了什么吗?为什么我的默认构造函数没有被调用,如果该对象尚未正确构造,我如何访问该对象?
I need to do some maintenance on an Objective-C application (updating it to use a new API), and having never used the language before, I'm a bit confused.
I have an Objective-C++ class which implements an interface from my API, and this is used within a block, however whenever it is accessed within the block, it fails with an access violation error (EXC_BAD_ACCESS).
Furthrer investigation shows that none of the constructors for the object in question are being called. It is declared within the containing scope, and uses the __block modifier.
To try and understand this, I made a quick scratch application, and found the same thing happens there:
class Foo
{
public:
Foo() : value(1) { printf("constructor"); }
void addOne() { ++value; printf("value is %d", value); }
private:
int value;
};
void Bar()
{
Foo foo1; // prints "constructor"
__block Foo foo2; // doesn't print anything
foo1.addOne(); //prints "2"
foo2.addOne(); //prints "1"
}
Can anyone explain what is happening here? Why isn't my default constructor being called, and how can I access the object if it hasn't been properly constructed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我了解,您的示例没有使用块本身,而是声明 foo2 由块使用。
这对 foo2 的处理做了有趣的事情,您可以阅读更多关于 此处。
希望有帮助。
As I understand it, your example there isn't using a block as such, but is declaring foo2 as to be used by a block.
This does funny things to the handling of foo2, which you can read more about here.
Hope that helps.
偶然发现这个老问题。这是一个早已修复的错误。现在
__block
C++ 对象已正确构造。如果在块中引用并且复制了该块,则堆副本将从原始位置移动构造,如果无法移动构造,则进行复制构造。Stumbled upon this old question. This was a bug that's long been fixed. Now
__block
C++ objects are properly constructed. If referenced in a block and the block is copied, the heap copy is move-constructed from the original, or copy-constructed if it cannot be move-constructed.