I can't find a way to return an array without dynamic memory allocation. I will explain it in detail using an example:
With dynamic memory allocation:
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() don't know the size of the array, so i used a struct to solve that problem:
struct deviceArray {
Device* devices;
int deviceCount;
};
Without dynamic memory allocation: I have no idea how to do this. I tried the following things:
- Pass by reference. Problem: we don't know the array size before scanning.
- Return without dynamic memory allocation (local variable) . Problem: the object no longer exist (of course).
std::vectoror similar classes.local pointeris always a disaster as address of that is not valid, upon exit of function. Hence, dynamic allocation is requiredstd::vectoruses dynamic memory allocation. The difference is that your function doesn't need to explicitly manage dynamically allocated memory - a vector manages its own memory.newthe memory is allocated on heap, so it would be valid to return the pointer of that allocation. If the object would be created on stack and the address would be returned using&then it would be invalid.