Reputation: 333
I need a function that returns an chunk of data (char *) with an arbitrary length. The function's caller needs both the array, and the size of the array. This array could dynamically be allocated inside the function, or be passed as an argument. There are multiple ways of achieving the same result. Now I was wondering what is considered the "cleanest" way of doing it in C++. I will give examples below.
Return array, modify length (as reference):
char *getData( int &length ) {
length = // set length
char *data = new char[ length ];
// fill data here
return data;
}
Return length, modify array (as reference):
int getData( char * &data ) {
int length = // set length
data = new char[ length ];
// fill data here
return length;
}
Return success-code, modify both array and length (as reference)
bool getData( int &length, char * &data ) {
int length = // set length
data = new char[ length ];
// fill data here
return true; // Successful
}
Fill provided array, return full length (might not get all data):
int getData( char *data, int maxLength ) {
int length = // set length
// fill data here, to max size of min( length, maxLength )
return length;
}
There might even be more possibilities to do this, but what is considered to be the "cleanest" way of doing this in C++ ?
Upvotes: 0
Views: 74
Reputation: 8492
None of them. If you're using C++, and not just C, go ahead and take advantage of the semantics it offers.
You really want to use std::vector
, specifically a std::vector<char>
. Don't roll your own or deal with C-style stuff, it's a waste of time.
Upvotes: 2
Reputation: 17131
You have several options. As commenters have mentioned the most C++ way is to use the standard containers. That's what they are there for. This way you also avoid a potential memory leak caused by manually new
ing data.
std::vector<char> getData() {
std::vector<char> res;
// fill vector with data of your choosing using push_back etc.
return res;
}
Another option if you must use c-style arrays is to use the new array_view
class published as part of the CppCoreGuidelines project under the GSL (Guideline Support Library).
See: https://github.com/Microsoft/GSL
And: https://github.com/isocpp/CppCoreGuidelines
However, I would recommend sticking to std::vector
unless you have a very good reason (such as a large legacy code base or interoperating with crucial and unupdateable libraries) to use c-style arrays.
Upvotes: 1