I'm confused in how to deal with a function that intends to return a class object.
Here I have a function connect
which accepts a url in the form of a char array and then creates an object of class Response which contains the response of visiting this url to return.
1> Return the response by value is the most straightforward, but people say copy constructor will make return by value kind of slow:
Response connect(char *); // declaration of connect
Response resp = connect(url_str);
2> Return the response by pointer is also easy to read, but need to handle deleting the pointer outside connect
:
Response * connect(char *); // declaration of connect
Response * resp = connect(url_str);
3> Declare an object of class Response before calling connect
and pass it into connect
via reference is good in reducing the risk of memory-leaks and also faster than return by value, but this makes the code counter-intuitive:
void connect(char *, Response &); // declaration of connect
Response resp;
connect(url_str, resp);
How will you handle this kind of case in C++? Any suggestion or experience are welcome.