【发布时间】:2013-07-31 09:35:49
【问题描述】:
我是智能指针的新手。不过,我对它有一个基本的了解。我观察到的是,智能指针必须以与其创建相反的顺序被销毁,否则智能指针可能会出现异常。考虑以下情况:
sharedPtr<abc> my_ptr(new abc); //smart pointer created. Instance counter = 1.
func1(my_ptr); //copy constructor in smart pointer called. Instance counter=2
func2(my_ptr); //copy constructor in smart pointer called. Instance counter=3
func3(my_ptr); //copy constructor in smart pointer called. Instance counter=4
现在,func3() 不是必须先退出,然后是 func2(),func1(),最后是 my_ptr。
问题:如果my_ptr 首先超出范围(并因此尝试删除abc),func1()、func2() 和func3() 仍然指的是@987654330,该怎么办? @(通过智能指针)?
【问题讨论】:
标签: c++ multithreading smart-pointers reference-counting