auto_ptr & share_ptr & unique_ptr
Using auto_ptr, you don’t need think about the memory deallocation, but there are also many arguments about it because of auto_ptr ownership translation.
void AutoPtrTest(void) { std::auto_ptr<int> p1 (new int(10)); //pass ownership std::auto_ptr<int> p2 = p1; std::cout << "p1 will raise exception:" << *p1 << std::endl; std::cout << "p2 is ok: " << *p2 << std::endl; }
In C++11, the auto_ptr is deprecated. The shared_ptr and unique_ptr are designed which have more security and comprehensive.
void AutoPtrTest(void) { std::auto_ptr<int> p1 (new int(10)); //pass ownership std::auto_ptr<int> p2 = p1; //here has a warning in GCC //std::cout << "p1 will raise exception:" << *p1 << std::endl; std::cout << "p2 is ok: " << *p2 << std::endl; std::shared_ptr<int> s1 (new int(10)); std::shared_ptr<int> s2 = s1; //share it. point to same address std::cout << "s1 is ok:" << *s1 << std::endl; std::cout << "s2 is ok: " << *s2 << std::endl; std::unique_ptr<int> u1 (new int(10)); // std::unique_ptr<int> u2 = u1; //cannot be compiled std::cout << "u1 is ok:" << *u1 << std::endl; // std::cout << "s2 is ok: " << *s2 << std::endl; }
In conclusion, auto_ptr could be replaced by shared_ptr or unique_ptr depending upon situation.
浙公网安备 33010602011771号