I was making a std::vector like clone for a fun little project in C++, and I've come across the following problem: I'm trying to implement the method pop_back but for some reason, I can't get it to work. The class I'm using is called Array and is defined in ../d_arrays/d_array.h and ../d_arrays/d_array.cpp I have a main.cpp file in the root folder. Here is what I have so far:
RootDir/d_arrays/d_array.h
#include <iostream>
using namespace std;
class Array {
public:
Array(int len);
void pop_back();
void print();
private:
int* _array = NULL;
int _len = 0;
};
RootDir/d_arrays/d_array.cpp
#include <iostream>
#include "d_array.h"
using namespace std;
Array::Array(int len) {
_array = new int[len];
_len = len;
}
void Array::pop_back() {
_len--; // reduce length by 1
int* tmp = new int[_len]; // create temp copy
for (int i = 0; i < _len; i++) {
tmp[i] = _array[i];
}
_array = tmp;
delete[] tmp;
}
void Array::print() {
for (int i = 0; i < _len; i++) {
cout << _array[i] << " ";
}
cout << endl;
}
RootDir/main.cpp
#include <iostream>
#include "d_arrays/d_array.h"
using namespace std;
int main() {
Array a = Array(10);
cout << "Before: ";
a.print();
a.pop_back();
cout << "After: ";
a.print();
return 0;
}
Im using g++ -o main main.cpp d_arrays/d_array.cpp to compile my code and ./main to run it.
whenever I run ./main I get the following output:
Before: 0 0 0 0 0 0 0 0 0 0
After: 0 0 118968336 21854 0 0 0 0 0
What is happening here?
pop_back. 2. The array's contents are never initialized in the initial array, thus, using any of those values is undefined. 3. You alsodelete[] tmpwhich is the new array you just allocated.std::swap(_array, tmp);instead of_array = tmp;_array = tmp; delete[] tmp;You deleted the new array since bothtmpand_arraypoint to the same memory.len--; // reduce length by 1-- And that is all you really need to do. All of that other code that attempts to resize the memory allocated is not necessary.pop_back()is supposed to be a constant-time operation. Yourpop_back()has linear time complexity, all due to the creation of memory and recopying. Imagine if the vector had a million elements --pop_back()would go through the gauntlet of decreasing the length (ok), but then reallocate 999,999 elements again and initialize them with data that you just deallocated. That does not make a lot of sense, especially since_lenis what controls the number of entries.