【发布时间】:2017-12-13 05:49:00
【问题描述】:
如果没有动态内存分配,我找不到返回数组的方法。我会用一个例子来详细解释一下:
使用动态内存分配:
Device* getConnectedDevices() {
// scan for devices.
Device *connectedDevices = new Device[deviceCount]; // Dynamically allocate memory for the Devices
// Get for each device an ID
return connectedDevices;
}
void doSomething() {
// some code
// I need a list with all the connected devices!!
Device *connectedDevices;
connectedDevices = getConnectedDevices();
// do something with the array
}
doSomething() 不知道数组的大小,所以我使用了一个结构来解决这个问题:
struct deviceArray {
Device* devices;
int deviceCount;
};
没有动态内存分配: 我不知道该怎么做。我尝试了以下方法:
- 通过引用传递。问题:我们在扫描之前不知道数组大小。
- 返回而不进行动态内存分配(局部变量)。问题:对象不再存在(当然)。
【问题讨论】:
-
不要手动分配任何东西,在 c++ 中只需使用
std::vector或类似的类。 -
返回
local pointer总是一场灾难,因为该地址在函数退出时无效。因此,需要动态分配 -
std::vector使用动态内存分配。不同之处在于您的函数不需要显式管理动态分配的内存 - 向量管理自己的内存。 -
@dlmeetei 使用
new,内存是在堆上分配的,因此返回该分配的指针是有效的。如果对象将在堆栈上创建并且地址将使用&返回,那么它将是无效的。 -
你无法避免动态内存,因为只有动态内存比函数持续时间更长。
标签: c++ arrays memory memory-management