提问人:Martian 提问时间:10/6/2020 更新时间:10/6/2020 访问量:28
具有堆内存分配的类,2 个实例共享一个指针(未分配要释放的指针)
Class with heap memory allocation, 2 instances share a pointer (pointer being freed was not allocated)
问:
我需要一些围绕 C++ 动态数组的包装器,因此具有以下属性的类:
class Dyn_array {
std::string name;
int length;
int* head;
}
此外,我必须重载/运算符,但我无法返回结果,因为我已经提到错误,问题可能出在构造函数/析构函数上:要么我调用某个析构函数两次,要么更可能是 2 个实例共享一个指针。是的,缩进是错误的,我不知道为什么 emacs 会这样。*
*=
#include <iostream>
#include <string>
class Dyn_array {
std::string name;
int length;
int* head;
public:
Dyn_array()
: name("Unknown"), length(0), head(nullptr)
{
std::cout << "Default constructor of " << name << " is being used.\n";
}
Dyn_array(std::string n_name, int n_length)
: name(n_name), length(n_length), head(new int[n_length])
{
for (int i = 0; i < n_length; i++) {
head[i] = 0;
}
std::cout << "Constructor with parameters of " << name << " is being used.\n";
}
void add(int n_element) {
if (head) {
head[length] = n_element;
}
else {
head = new int(n_element);
}
length++;
}
Dyn_array(std::string n_name, int* array, int size)
: name(n_name), length(0), head(nullptr)
{
for (int i = 0; i < size; i++) {
add(array[i]);
}
std::cout << "Constructor with array of " << name << " is being used.\n";
}
~Dyn_array() {
if (head) {
delete[] head;
head = nullptr;
length = 0;
}
std::cout << "Destructor of " << name << " with address " << head << " is being used.\n";
}
int& operator[](int i) {
return head[i];
}
int operator[](int i) const {
return head[i];
}
Dyn_array(const Dyn_array& rhs) {
(*this).~Dyn_array();
std::cout << "Copy constructor is being used.\n";
for (int i = 0; i < rhs.length; i++) {
add(rhs[i]);
}
}
Dyn_array& operator*= (const Dyn_array& rhs) { // HERE------------
Dyn_array temp; // Creating an instance to store result
for (int i = 0; i < length; i++) {
bool check = false;
for (int j = 0; i < rhs.length; i++) {
if (head[i] == rhs.head[j]) {
check = true;
}
}
if (check) {
temp.add(head[i]);
}
}
temp.add(53); // For debugging
(*this) = Dyn_array(temp); // Copy constructor calling
return (*this);
}
void print() {
if (head) {
for (int i = 0; i < length; i++) {
std::cout << head[i] << " ";
}
std::cout << '\n';
}
else {
std::cout << "Array is empty.\n";
}
}
};
int main() {
int arr1[3] = {1, 2, 3};
int arr2[4] = {1, 2, 3, 4};
Dyn_array a("first", arr1, 3);
Dyn_array b("second", arr2, 4);
a.print();
b.print();
b *= a;
a.print();
b.print();
}
答: 暂无答案
评论
(*this).~Dyn_array();
你为什么要这么做?你销毁,然后继续使用它。这看起来不对this
add
head = nullptr
add
不增加数组的大小,当为 null 时分配单个元素而不是数组head
add()
operator[]