auto_ptr is not dereferencable

清泛原创

错误如下图所示:

错误代码示例:

// Example : Transferring ownership from
//            one auto_ptr to another
void testAutoPtr6()
{
	std::auto_ptr<TC> pt1(new TC);
	std::auto_ptr<TC> pt2;

	pt1->someFunc(); // OK

	pt2 = pt1;  // now pt2 owns the pointer, and pt1 does not
	std::cout << "Content of pt1 is " << pt1.get() << std::endl;
	std::cout << "Content of pt2 is " << pt2.get() << std::endl;

	pt2->someFunc(); // OK

	pt1->someFunc(); // error! following a null pointer

} // as we go out of scope, pt2's destructor
// deletes the pointer, but pt1's does nothing

auto_ptr在拷贝时会转移内存控制权,例子中pt1赋值给pt2后,将内存管理权转移给pt2, 此时pt1指针为NULL。

auto_ptr dereferencable

分享到:
评论加载中,请稍后...
创APP如搭积木 - 创意无限,梦想即时!
回到顶部