greetings!
ive got a sexy little method, which allocates some dynamic memory to read some data from a socket and return its contents (shortened slightly for better reading)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
|
std::string WinSock::Client::Receive(int iLen, int iChunkSize) {
int lenRecv;
char* cRecv;
std::stringstream ssOut;
if(iLen < iChunkSize)
lenRecv = iChunkSize;
else
lenRecv = iLen;
cRecv = new char[lenRecv];
lenRecv = recv(*this->wsSocket, cRecv, lenRecv, 0);
switch (lenRecv)
{
case 0:
delete [] cRecv;
throw Logger(lenRecv, "Server disconnected..");
break;
case SOCKET_ERROR:
delete [] cRecv;
throw Logger(lenRecv, "Error: recv. function");
break;
default:
if(lenRecv >= iLen)
cRecv[iLen] = '\0';
else
cRecv[lenRecv] = '\0';
ssOut << cRecv;
delete [] cRecv;
return this->cleanString(ssOut.str());
}
}
|
and a little overdrive!:
1 2 3 4
|
std::string WinSock::Client::Receive(int iLen) {
return this->Receive(iLen, std::numeric_limits<int>::max());
}
|
note the cleanString method isnt further relevant so im saving that overhead
> now my first concern is that im using a stringstream, to attain the possibility to delete the cRecv pointer before its returned
> which brings me to the second concern, having to spam the delete across the switch (even though its more aesthetics), but still needing to chop off the data at the appropriate positions
and having two linked concerns already lets me assume i might be doing something wrong
is there a cleaner way to return the pointer, still being able to delete it properly?
and for the overdrive method; is there a better/cleaner way to flushing a string through the returns?
preferably i wouldnt want to go down the malloc() function road =)