误解了析构函数的工作原理?

Pip*_*les 2 c++ class object

classy.h

struct Stack{ 
    int *arr;
    int numElements;
    int capacity;
};

class Point { 

private: 
 Stack *newStack;
public: 
  Point (int cap); 
  int returncap (); 
  ~Point(); 
}; 
Run Code Online (Sandbox Code Playgroud)

我不认为问题是h文件,而是两个cc文件中的一个

classy.cc

    #include <iostream> 
    #include "classy.h"

    using namespace std;

    Point::Point(int cap){
        newStack = new Stack;
        newStack->numElements = 0;
        newStack->arr = new int [cap];
        if(newStack->arr == NULL) {
        newStack->capacity = 0;
        }
        else {
        newStack->capacity = cap;
        }
    }

    Point::~Point(){ 
        delete newStack->arr;
        delete newStack;
    } 

    int Point::returncap() {
        return newStack->capacity;
    }
Run Code Online (Sandbox Code Playgroud)

main.cc

#include <iostream> 
#include "classy.h"

using namespace std;


int main() { 
  int x;
  cout << "Please insert cap: "<< endl;
  cin >> x;
  Point p (x); 
  cout << p.returncap();
  p.~Point(); 
  return 0; 
} 
Run Code Online (Sandbox Code Playgroud)

我将析构函数称为错误,还是我执行它?或者是他缺少的一点?在程序退出之前基本上获得一个内存映射.

Joh*_*nck 5

这是错误的,在main()中:

p.~Point();
Run Code Online (Sandbox Code Playgroud)

在C++中,您几乎不需要显式调用析构函数.相反,当"自动"(堆栈,默认类型的分配)变量超出范围,或者当您调用delete分配的内容时,它们会被"自动"调用new.你明确调用析构函数的唯一一次是当你使用"placement new"来明确地构造对象时......这是大多数程序员从未做过的事情.

删除上面的行,您的代码应该更好.