С++, Почему не срабатывает деструктор?
#include
class powers
{
public:
int *x = new int();
powers(int* n)
{
this->x = new int(*n);
std::cout << "1" << std::endl;
};
int getX()
{
return *x;
};
powers(const powers& obj)
{
this->x = new int(*obj.x);
std::cout << *x << std::endl;
std::cout << "2" << std::endl;
};
~powers()
{
delete[] x;
std::cout << "3" << std::endl;
};
};
int main()
{
setlocale(LC_ALL, "RUS");
int zxc = 10;
powers* a = new powers(&zxc);
std::cout << a->getX();
powers* b = new powers(*a);
return 0;
}
#include <algorithm>
#include <iostream>
#include <iomanip>
using namespace std;
class Powers {
public:
Powers() : n(0), x(nullptr) {}
Powers(const size_t n) : n(n), x(new int [n]) {
memset(x, 0, n * sizeof(x[0]));
}
Powers(const size_t n, int value) : n(n), x(new int[n]) {
for (auto& v : *this) v = value;
}
Powers(const Powers& p) : n(p.n), x(new int[n]) {
copy(p.x, p.x + n, x);
}
Powers(Powers&& p) : n(p.n), x(move(p.x)) {}
Powers(initializer_list<int> li) : n(li.size()), x(new int[n]) {
copy(li.begin(), li.end(), x);
}
~Powers() {
if (x != nullptr) {
delete[] x;
x = nullptr;
}
}
Powers& operator=(const Powers& p) {
if (&p != this) {
delete[] x;
n = p.n;
x = new int[n];
copy(p.x, p.x + n, x);
}
return *this;
}
Powers& operator=(Powers&& p) {
if (&p != this) {
delete[] x;
n = p.n;
x = p.x;
p.x = nullptr;
}
return *this;
}
int& operator[](int i) {
return x[i];
}
const int operator[](int i)const {
return x[i];
}
size_t size()const {
return n;
}
int* begin() {
return x;
}
int* end() {
return x + n;
}
const int* begin()const {
return x;
}
const int* end()const {
return x + n;
}
private:
size_t n;
int* x;
};
void show(const Powers& box, const streamsize w = 3) {
for (const auto x : box) cout << setw(w) << x;
puts("");
}
int main() {
Powers box{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
show(box);
auto test = Powers{ 1, 2, 3, 4, 5 };
show(test);
test = box;
show(test);
Powers foo(9);
show(foo, 3);
foo[4] = 99;
show(foo);
int n = 10, m = 0;
for (auto& x : foo) x = n * ++m;
show(foo);
foo = Powers{ 11, 22, 33, 44, 55, 66, 77, 88, 99 };
show(foo);
for (auto i = 0U; i < foo.size(); ++i) cout << setw(3) << foo[i];
puts("");
Powers bar(9, 5);
show(bar);
system("pause > nul");
}
а почему он должен срабатывать?
delete-то нету
а ещё у тебя внутри класса утечка: перед выполнением тела конструктора в x записывается new int(), а потом начинается конструктор, и x перезаписывается
и квадратные скобки у delete не нужны, тут не массив выделяется