Nov 25, 2017 at 1:48pm UTC
I have a int* that named arr and have a function that called in main(); this function named push_back that add a int to arr; I also have a function named pop_back that delete arr[the_last_member].
This is my project:
***************************************************************************
main.cpp :
#include<iostream>
#include "vector.h"
using std::cout;
using std::endl;
int main()
{
vector v;
v.push_back(0);
v.push_back(1);
v.pop_back(); //this delete arr[the_last_member]
return 0;
}
*********
vector.h:
#pragma once
#include<iostream>
class vector
{
public:
vector();
void push_back(int n);
void pop_back();
~vector();
int* arr;
int static cnt;
};
**********
vector.cpp:
#include "vector.h"
vector::vector()
{
}
void vector::push_back(int n)
{
int static cnt{};
cnt++;
arr = new int[cnt];
arr[cnt - 1] = n;
}
void vector::pop_back()
{
cnt--;
arr = new int[cnt];
}
vector::~vector()
{
delete[] arr;
}
but in this program old members of arr will be deleted.
How can I resolve it?
Last edited on Nov 25, 2017 at 1:49pm UTC
Nov 25, 2017 at 4:31pm UTC
actually, they aren't being deleted, they are simply lost, drifting in the memory sea.
consider to move them, one by one, to their new destination.