首页 > 解决方案 > 是否有命令检查我的动态数组中的对象是动态的还是静态的?

问题描述

我用模板制作了一个动态数组。问题是,当我不保留指针时(例如:),Tab<string> da;我的析构函数不必清除它并抛出由delete arr[i];. 我的问题是我是否可以放置一些 if 条件(我将在其中放置clear()方法),它会告诉我我的数组是否保留指针。以最简单的方式clear(),当我保持指针时,我可以在 main 中使用,但我的老师希望我像上面写的那样做。

我尝试使用is_pointer,但它不起作用或我使用错误。有什么建议么?

#ifndef TABLICA_H
#define TABLICA_H

#include <iostream>
#include <type_traits>

using namespace std;

template<class T>
class Tab
{
public:

int size = 0;
int max_size = 1;
T* arr;
bool isDynamic = false;


Tab()
{
    arr = new T[max_size];
}

~Tab()
{
    clear();
    delete[] arr;
}


void check_size()
{
    if (size == max_size)
    {
        max_size = max_size * 2;
        T* arr2 = new T[max_size];
        for (int i = 0; i < size; i++)
        {
            arr2[i] = arr[i];
        }
        delete[] arr;
        arr = arr2;
    }
}

void push_back(const T& value)
{
    check_size();
    arr[size] = value;
    size++;
}

T return_by_index(int index)
{
    if (index<0 || index > size)
    {
        return NULL;
    }
    return arr[index];
}

bool replace(int index, const T& value)
{
    if (index<0 || index > size)
    {
        return false;
    }
    arr[index] = value;
    return true;
}

void print(int number)
{
    cout << "Rozmiar obecny: " << size << endl;
    cout << "Rozmiar maksymalny: " << max_size << endl;
    cout << "Adres tablicy: " << arr << endl;
    cout << "Kilka poczatkowych elementow tablicy " << "(" << number << ")" << endl;
    for (int i = 0; i < number; i++)
    {
        cout << *arr[i] << endl;
    }
}

void clear()
{
    for (int i = 0; i < size; i++)
    {
        delete arr[i];
    }
}

};

#endif 


//Source:

#include <iostream>

struct object
{
int field1;
char field2;

object()
{
    field1 = rand() % 10001;
    field2 = rand() % 26 + 'A';
}

};

ostream& operator<<(ostream& out, const object& o)
{
return out << o.field1 << " " << o.field2;
}

int main()
{

Tab < object* >* da = new Tab < object* >();
delete da;
system("PAUSE");
return 0;

标签: c++arraysdynamicstaticdynamic-arrays

解决方案


推荐阅读