c++ - 是否有命令检查我的动态数组中的对象是动态的还是静态的?
问题描述
我用模板制作了一个动态数组。问题是,当我不保留指针时(例如:),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;
解决方案
推荐阅读
- cmake - CMake 为每个配置链接器标志设置
- javascript - 这是我的代码的问题还是 discord.js 的问题?
- xcode - 函数“yyback”的隐式声明在 C99 中无效
- python - 如何比较不同类型的两个值并从抓取的表数据中确定最大值
- node.js - 为什么 node -v 命令不能在 Windows 上使用 wsl2 Ubuntu 20.04
- python - 基于另一列生成新列
- angular - 使用 API 时如何解决 Angular CORS 错误
- python-3.x - google colaboratory 在线开发环境中是否提供 python 串行通信库?
- javascript - 循环获取所有元素,在哪里使用 forEach?
- python - 删除数据框中的行