Class 内的动态内存分配
Dynamic Memory Allocation inside Class
如何在 class 中动态分配内存?
为了澄清我的问题,我举了一个例子。我会构造一个 A 的实例 a 并将其复制到 b 中。使用后 a and b 将被析构,分配的内存将在析构函数中被释放两次。
那么我该如何处理这种情况?
#include <stdlib.h>
class A {
public:
char * allocatedMemory;
A(int length) {
allocatedMemory = (char *) malloc(sizeof(char) * length);
}
~A(){
free(allocatedMemory);
}
};
int main() {
A a = A(50);
A b = a;
return 0;
}
PS:了解上下文:我试图通过示例弄清楚 std::string 如何分配和释放内存。当然只有基本配置。
您好,您遇到的问题是由浅拷贝引起的。如果您不显式提供复制构造函数,则编译器将提供默认复制构造函数以使用现有对象初始化一个对象。默认复制构造函数执行按位复制。 IE。只需将存储在一个对象指针中的地址复制到另一个对象。为了避免这种双重释放问题,你需要做深拷贝。编写您自己的复制构造函数,在该复制构造函数中使用 new 显式地为您的字符指针分配内存,然后使用 memcpy() 复制实际内容。希望这会有所帮助。
#include <stdlib.h>
class A
{
public:
char * allocatedMemory;
int length;
A(int length):length(length)
{
// i am ignoring exception due to failure in new to keep code simple
this->allocatedMemory = new char[length];
}
A(const A& obj)
{
this->allocatedMemory = new char[obj.length];
memcpy(this->allocatedMemory, obj.allocatedMemory, obj.length);
this->length = obj.length;
}
A& operator=(const A& obj)
{
if(this != &obj)
{
if(this->length == obj.length)
{
memcpy(this->allocatedMemory, obj.memory, obj.length);
}
else
{
delete[] this->allocatedMemory;
this->allocatedMemory = NULL;
this->allocatedMemory = new char[obj.length];
memcpy(this->alocatedMemory, obj.allocatedMemory, obj.length);
this->length = obj.length;
}
}
return *this;
}
~A()
{
if(allocatedMemory)
delete[] allocatedMemory;
}
};
int main()
{
A a = A(50);
A b = a;
return 0;
}
如何在 class 中动态分配内存?
为了澄清我的问题,我举了一个例子。我会构造一个 A 的实例 a 并将其复制到 b 中。使用后 a and b 将被析构,分配的内存将在析构函数中被释放两次。
那么我该如何处理这种情况?
#include <stdlib.h>
class A {
public:
char * allocatedMemory;
A(int length) {
allocatedMemory = (char *) malloc(sizeof(char) * length);
}
~A(){
free(allocatedMemory);
}
};
int main() {
A a = A(50);
A b = a;
return 0;
}
PS:了解上下文:我试图通过示例弄清楚 std::string 如何分配和释放内存。当然只有基本配置。
您好,您遇到的问题是由浅拷贝引起的。如果您不显式提供复制构造函数,则编译器将提供默认复制构造函数以使用现有对象初始化一个对象。默认复制构造函数执行按位复制。 IE。只需将存储在一个对象指针中的地址复制到另一个对象。为了避免这种双重释放问题,你需要做深拷贝。编写您自己的复制构造函数,在该复制构造函数中使用 new 显式地为您的字符指针分配内存,然后使用 memcpy() 复制实际内容。希望这会有所帮助。
#include <stdlib.h>
class A
{
public:
char * allocatedMemory;
int length;
A(int length):length(length)
{
// i am ignoring exception due to failure in new to keep code simple
this->allocatedMemory = new char[length];
}
A(const A& obj)
{
this->allocatedMemory = new char[obj.length];
memcpy(this->allocatedMemory, obj.allocatedMemory, obj.length);
this->length = obj.length;
}
A& operator=(const A& obj)
{
if(this != &obj)
{
if(this->length == obj.length)
{
memcpy(this->allocatedMemory, obj.memory, obj.length);
}
else
{
delete[] this->allocatedMemory;
this->allocatedMemory = NULL;
this->allocatedMemory = new char[obj.length];
memcpy(this->alocatedMemory, obj.allocatedMemory, obj.length);
this->length = obj.length;
}
}
return *this;
}
~A()
{
if(allocatedMemory)
delete[] allocatedMemory;
}
};
int main()
{
A a = A(50);
A b = a;
return 0;
}