Can you call the destructor? Classes.

If so, how?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Blah{
  public:
  void fnc() {}
  ~Blah(){
    std::cout << "blah";
  }
};

int main(){
  Blah blah;
  // deconstruct blah
  blah.fnc(); // nope sry blah is gone.
  return 0;
}
Yes, but it's not often a good idea ...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

class Blah{
  public:
  void fnc() {std::cout << "in fnc ...\n";}
  ~Blah(){
    std::cout << "bye-bye, blah\n";
  }
};

int main(){
  Blah blah;
  // deconstruct blah
  blah.fnc();
  blah.~Blah();
  return 0;
}
^ The above function will print "bye-bye, blah" twice, in case that wasn't clear.

And look what happens when you make a vector!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <vector>

class Blah {
  public:
  Blah() {
      std::cout << "hi-hi, blah\n";
  }
  ~Blah() {
    std::cout << "bye-bye, blah\n";
  }
};

int main(){
    
  std::vector<Blah> blahs;
  
  blahs.push_back(Blah());
  blahs.push_back(Blah());
  blahs.push_back(Blah());

  return 0;
}

hi-hi, blah
bye-bye, blah
hi-hi, blah
bye-bye, blah
bye-bye, blah
hi-hi, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah



With explicitly printed move ctors:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

class Blah {
  public:
  Blah(Blah&& blah)
  {
    std::cout << "hi-hi, blah MOVE\n";   
  }
  Blah() {
      std::cout << "hi-hi, blah\n";
  }
  ~Blah() {
    std::cout << "bye-bye, blah\n";
  }
};

int main(){
    
  std::vector<Blah> blahs;
  
  blahs.push_back(Blah());
  blahs.push_back(Blah());
  blahs.push_back(Blah());

  return 0;
}

hi-hi, blah
hi-hi, blah MOVE
bye-bye, blah
hi-hi, blah
hi-hi, blah MOVE
hi-hi, blah MOVE
bye-bye, blah
bye-bye, blah
hi-hi, blah
hi-hi, blah MOVE
hi-hi, blah MOVE
hi-hi, blah MOVE
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
bye-bye, blah
Last edited on
@lastchance thanks!
@Ganado Whaaaaaat is happening here?? I don’t understand why. Is it because it is making a new array of Blahs each day time? But that would the constructor too. What? Edit: oh wait see the moves oops.
Last edited on
does it actually free up the memory?
There are no memory leaks in any of the code examples above. All memory is freed.

What's happening with my last example is just to demonstrate all the stuff that could potentially be happening when you have bunches of objects. The temporary objects ("Blah()") have their own construction + destruction, and when a vector re-allocates, it also has to re-create objects again. That's why it ends up looking so complicated.
Topic archived. No new replies allowed.