- // TestAutoPtr.cpp : Defines the entry point for the console application.
- //
- #include "stdafx.h"
- #include <vector>
- #include <memory>
- class A
- {
- public:
- A();
- ~A();
- void SetA(int a);
- int GetA() const;
- private:
- int m_a;
- };
- A::A()
- :m_a(0)
- {
- }
- A::~A()
- {
- }
- void A::SetA(int a)
- {
- m_a = a;
- }
- int A::GetA() const
- {
- return m_a;
- }
- void Foo(std::auto_ptr<A> apA)
- {
- int i=3;
- }
- void Foo(std::unique_ptr<A> upA)
- {
- int j=3;
- }
- void Foo2(std::auto_ptr<A>& apA)
- {
- int i=3;
- std::auto_ptr<A> ap(new A());
- apA = ap;
- }
- std::auto_ptr<A> Foo()
- {
- std::auto_ptr<A> ap(new A());
- return ap;
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- //std::auto_ptr<A> apA(new A());
- //std::unique_ptr<A> upA(new A());
- // std::unique_ptr<A> upAOther = upA; //It's compile error
- //std::unique_ptr<A> upAOther(upA); //It's compile error
- //std::unique_ptr<A> upAnother = std::move(upA);
- /*
- unique_ptr(unique_ptr&& _Right)
- : _Mybase(_Right.release(),
- _STD forward<_Dx>(_Right.get_deleter()))
- { // construct by moving _Right
- }
- */
- //std::unique_ptr<A> upA2(new A[2]); // It's wrong, which will have memory leak
- // msdn for unique_ptr:
- // http://msdn.microsoft.com/en-us/library/ee410601.aspx
- // The unique_ptr class supersedes auto_ptr, and can be used as an element of STL containers.
- /*
- std::unique_ptr<A[]> upA3(new A[2]);
- upA3[0]->SetA(3);
- */
- /*
- std::unique_ptr<A> upMyA1(new A());
- std::unique_ptr<A> upMyA2(new A());
- std::vector<std::unique_ptr<A> > vecPointer;
- vecPointer.push_back(std::move(upMyA1));
- vecPointer.push_back(std::move(upMyA2));*/
- // It's wrong to make the auto_ptr<A> as the parameter
- // The resource gets deleted
- /*
- std::auto_ptr<A> upMyA3(new A());
- Foo(upMyA3);
- */
- // It's also not recommended to pass unique_ptr<A> as the parameter
- /*
- std::unique_ptr<A> upMyA4(new A());
- Foo(std::move(upMyA4));
- */
- // The return value can't be template
- //std::auto_ptr<A> apMyA5 = Foo();
- // How about make the auto_ptr as the & parameter?
- // It seems can work well
- std::auto_ptr<A> apMyA6;//(new A());
- Foo2(apMyA6);
- return 0;
- }