C++/Pointer/Auto Pointer — различия между версиями
| Admin (обсуждение | вклад) м (1 версия: Импорт контента...) | Admin (обсуждение | вклад)  м (1 версия: Импорт контента...) | 
| (нет различий) | |
Текущая версия на 10:27, 25 мая 2010
Demonstrate an auto_ptr.
 
#include <iostream>
#include <memory>
using namespace std;
class X {
public:
  X() { 
     cout << "constructing\n"; 
  }
  ~X() { 
     cout << "destructing\n"; 
  }
  void f() { 
     cout << "Inside f()\n"; 
  }
};
int main()
{
  auto_ptr<X> p1(new X), p2;
  p2 = p1;            // transfer ownership
  p2->f();
  
  X *ptr = p2.get();  // can assign to a normal pointer
  ptr->f();
  return 0;
}
Demonstrates the use of auto_ptr.
  
#include <iostream>
#include <memory>
using namespace std;
   
class MyClass {
public:
  MyClass() { 
     cout << "constructing\n"; 
  }
  ~MyClass() { 
     cout << "destructing\n"; 
  }
  void f() { 
     cout << "Inside f()\n"; 
  }
};
   
int main()
{
  auto_ptr<MyClass> myClassPointer1(new MyClass), myClassPointer2;
   
  myClassPointer2 = myClassPointer1; 
  myClassPointer2->f();
   
  MyClass *ptr = myClassPointer2.get();
  ptr->f();
   
  return 0;
}