我定义了两个简单的 Python 函数,它们接受单个参数、引发异常并处理引发的异常。一个函数在引发/处理之前使用变量来引用异常,另一个函数则不使用:
def refcount_unchanged(x):
try:
raise Exception()
except:
pass
def refcount_increases(x):
e = Exception()
try:
raise e
except:
pass
Run Code Online (Sandbox Code Playgroud)
结果函数之一增加了refcount其输入参数的 pythons,另一个则没有:
import sys
a = []
print(sys.getrefcount(a))
for i in range(3):
refcount_unchanged(a)
print(sys.getrefcount(a))
# prints: 2, 2, 2, 2
b = []
print(sys.getrefcount(b))
for i in range(3):
refcount_increases(b)
print(sys.getrefcount(b))
# prints: 2, 3, 4, 5
Run Code Online (Sandbox Code Playgroud)
谁能解释为什么会发生这种情况?
我只是写了一些探索性代码来巩固我对Objective-C的理解,我遇到了这个我不太了解的例子.我定义了这个方法并运行代码:
- (NSString *)stringMethod
{
NSString *stringPointer = [[NSString alloc] initWithFormat:@"string inside stringPointer"];
[stringPointer release];
[stringPointer release];
NSLog(@"retain count of stringPointer is %i", [stringPointer retainCount]);
return stringPointer;
}
Run Code Online (Sandbox Code Playgroud)
运行代码并调用此方法后,我注意到一些事情:
通常情况下,如果我尝试在达到零保留计数后访问被认为已解除分配的内容,则会出现EXC_BAD_ACCESS错误.在这里,我得到了malloc"双重免费"错误.这是为什么?
无论我添加多少行"[stringPointer release]",NSLog报告保留计数为1.当我添加更多版本时,我只会得到更多"双重免费"错误.为什么发布语句不能按预期工作?
虽然我已经过度发布了stringPointer并且我收到了一堆"双重免费"错误,但返回值仍然可以正常工作(我在主代码中有另一个报告返回值的NSLog).该程序继续正常运行.再一次,有人可以解释为什么会这样吗?
这些例子相当简单,但我试图全面掌握正在发生的事情.谢谢!
难道我的理解是,新标准的权利shared_ptr并不需要使用引用计数?只有它可能以这种方式实现?
我可以想象一个以某种方式使用隐藏链表的实现.在N3291"20.7.2.2.5.(8)shared_ptr观察者[util.smartptr.shared.obs]"
[注意:use_count()不一定有效. - 结束说明]
这给了我这个想法.
为了引用计数,使用std :: tr1 :: shared_ptr和下面的示例代码一样安全正确吗?(这只是一个特定的示例,该类可以包含任何其他内容(void*)而不是FILE*)
class File
{
public:
File(const char* path, const char* mode) :
_refcount(new int(0))
{
this->_file = fopen(path, mode);
}
~File()
{
if (this->_refcount.unique())
{
if (this->_file != NULL)
{
fclose(this->_file);
}
}
}
int write(void* buff, size_t size)
{
fwrite(buff, size, 1, this->_file);
}
private:
FILE* _file;
std::tr1::shared_ptr<int> _refcount;
};
Run Code Online (Sandbox Code Playgroud) std::shared_ptr需要在堆上分配一个控制块来保存引用计数.我从http://ootips.org/yonat/4dev/smart-pointers.html学到了另一种方法,它将所有引用保存在双向链表中.它不需要额外的分配也不需要计数器,但参考对象本身更大.
有没有基准或任何明确的理由表明一个实施比其他实施更好?
我有一个工作正常的应用程序.然后我尝试将导航控制器嵌入到tabbarcontroller中,接下来我知道我在编译期间开始收到这些错误.
谁会知道为什么这些会发生?某些设置是否未经检查或意外检查?
谢谢,亚历克斯
我遗漏了一些关于共享/弱指针的东西:
当使用shared_ptr构造a时make_shared,仅使用一个内存分配(为控制块和对象本身分配内存).当最后一次shared_ptr被摧毁但是还weak_ptr剩下什么时会发生什么?此时必须取消分配托管对象.但是如果分配的内存make_shared被释放,那将使弱指针无效,因为相同的释放会破坏控制块.
我有以下代码:
NSDictionary *dict = @{ @"myKey" : @"myValue" };
Run Code Online (Sandbox Code Playgroud)
我应该发布dict使用release或autorelease?
或者我没有这个对象,所以我不应该自己发布它?
注意:我使用手动引用计数(ARC已禁用).
由于共享单例实例将始终存在,我们是否可以安全地使用[unowned self]该单例类中的所有闭包?
singleton memory-management reference-counting swift unowned-references