我已经写了以下代码来实现一个栈。
在代码中,当我注释掉了s.pop()方法时,析构函数没有被调用。
有人可以解释这种行为背后的技术原因吗?
我尝试理解在C++类中如何调用析构函数。
#include<iostream>
using namespace std;
class stack
{
public:
int *top;
int size, capacity;
stack(int c):capacity(c){
size = 0;
top = new int[capacity];
capacity = capacity - 1;
}
~stack() // deleting the stack at the end of program
{
delete[] top;
top = NULL;
cout << "deleted the stack" << endl;
}
void push(int data)
{
// Is there is a space
if(is_stackFull())
{
cout << "stack is full" << endl;
return;
}
// populate the data
*top = data;
// updating the stack variables
top += 1;
size += 1;
return;
}
void pop()
{
// is stack empty
if(is_stackEmpty())
{
cout << "stack is empty" << endl;
return;
}
// update the stack variables
top -= 1;
size -= 1;
return;
}
bool is_stackFull()
{
return (size == capacity);
}
bool is_stackEmpty()
{
return (size == 0);
}
};
int main()
{
stack s(10);
s.push(15);
//s.pop(); // what happens to the output when i comment out this code?
return 0;
}
在代码中,当我注释掉了s.pop()方法时,析构函数没有被调用。
有人可以解释这种行为背后的技术原因吗?
我尝试理解在C++类中如何调用析构函数。
push
操作会增加top
指针的值,使其不再指向你分配的内存的起始位置。试图删除它将导致未定义的行为。https://godbolt.org/z/7Phr5q3hv 你需要提出一个不同的方案,以确保你始终可以访问最初的分配内存。 - Retired Ninjapush
操作会增加top
指针的值,使其不再指向你分配的内存的起始位置。试图删除它将导致未定义的行为。https://godbolt.org/z/7Phr5q3hv 你需要想出一个不同的方案,以确保你始终可以访问最初的分配。 - Retired Ninja