I have the following code:
src/main.cpp
:
#include <include/array.hpp>
int main() {
int temp[] = {1, 2, 3, 4, 5};
sdizo::array<int> a(temp, 5);
print_array(a);
return 0;
}
include/array.hpp
#pragma once
#include <string.h>
#include <iostream>
namespace sdizo {
template <class T>
class array {
private:
T* data;
int length;
public:
array();
array(T* d, int len);
~array();
T* begin();
T* end();
};
template <typename T>
array<T>::array() {
data = nullptr;
length = 0;
}
template <typename T>
array<T>::array(T* d, int len) {
length = len;
this->data = new T[len];
memcpy(this->data, d, sizeof(d[0]) * len);
}
template <typename T>
array<T>::~array() {
delete[] this->data;
}
template <typename T>
T* array<T>::begin() {
return &data[0];
}
template <typename T>
T* array<T>::end() {
return &data[length];
}
template <typename T>
void print_array(array<T> ar) {
for (auto x : ar) {
std::cout << x << " ";
}
std::cout << '\n';
}
}
Compiling it with: g++ src/*.cpp -I./ -std=c++1z -g -o bin/sdizo1
Now running it gives the following error:
I've noticed that when I didn't print the array, then no errors occured. I thought about passing the array by reference, cause for now it would create a local copy and maybe the error was caused by calling the destructor twice. So void print_array(array<T> &ar)
instead void print_array(array<T> ar)
worked.
The problem is gone now, but why is that. I know that probably the ~array()
was called twice, or something like that, on the same memory location, but why. Isn't the C++ compiler smart enough to detect those kind of things? Or should I always pass by reference, or is there a way to pass by value and not receive those kind of errors with a structure with custom made destructor?
I know that it will be probably boring for many ppl smarter than me, but hey, he that nothing questioneth, nothing learneth.