농담곰담곰이의곰담농

[객체지향프로그래밍(2)] 소멸자(Destructor)

by 브이담곰

🌜 요즘 1주일 반동안 질의응답하느라 수업진도를 나가지 않았다. 내 입장에서는 복습할 시간이 늘어나니까, 좋긴한데 한편으로는 새로운게 배우고 싶긴하당..ㅎㅎ

 

📌 Destructor

       -  called automatically at the end of the object's life in charge of releasing this memory.

       -  no arguments and returns nothing, not even void.

       -  uses the class name as its own name, but preceded with a tilde sign (~):

// destructors
#include <iostream>
#include <string>
using namespace std;

class Example4 {
    string* ptr;
  public:
    // constructors:
    Example4() : ptr(new string) {}
    Example4 (const string& str) : ptr(new string(str)) {}
    // destructor:
    ~Example4 () {delete ptr;}
    // access content:
    const string& content() const {return *ptr;}
};

int main () {
  Example4 foo;
  Example4 bar ("Example");

  cout << "bar's content: " << bar.content() << '\n';
  return 0;
}

 

✔ If prgrammers call the destructor before the program ended. That way means just calling function of the name ~desctroctor();.

  It's not mean the objects' delete, after calling the objects' destructor forcely while the project running. Real destrocter is called at the end of the project. 

 

 

🙋‍♀️  Case of calling destructor by forced.

class Sample()
{
private:
   int a;
public:
   ~Sample();
   Sample(int _a);
};

Sample::Sample(int _a) : a(_a)
{
   cout<<"create : " << _a << endl;
}

Sample::~Sample
{
   cout<<"delete : " << _a << endl;
}

int main()
{
   Sample sample_1(1);
   Sample sample_2(2);
   sample_1.~Sample(); //just call ~sample as function. not destructor type.
   cout<<"--------program finish----------"<<endl;
   return 0;
}
//now real destroctors are called.

 

 

 

블로그의 정보

농담곰담곰이의곰담농

브이담곰

활동하기