c++ auto_ptr類 智慧指標

心鑫發表於2014-03-27

int main() {
	std::auto_ptr<int> p;
	std::auto_ptr<int> p2;
	p = std::auto_ptr<int>(new int);
	*p = 11;
	p2 = p;
//	std::cout << "p points to " << *p << '\n'; //p is now null-pointer auto_ptr
	std::cout << "p2 points to " << *p2 << '\n';  //此時輸出的是11
	p2.reset(new int);                            //上個new 被delete
	std::cout << "p2 points to " << *p2 << '\n';  //此時輸出 0

	int * p3=p2.release();
//	std::cout << "p2 points to " << *p2 << '\n'; //p2 不可用了
	cout << "p3 points to " << *p3 << '\n'; //輸出0
	return 0;

}

p = std::auto_ptr<int>(new int); 

引數new 出來的指標沒通過delete釋放。 

用於基本型別

需引用#include <memory>>

相關文章