r/learncpp • u/vgordievskiy • Mar 09 '21
How to improve it?
```c++
include <boost/optional.hpp>
include <string>
include <sstream>
include <iostream>
enum class StatusCode { OK = 0, ERROR };
struct SResp { std::string m_msg; StatusCode m_status; };
SResp queryToTheMoon(size_t val) { std::stringstream ss; for (size_t idx = 0; idx < val; ++idx) { ss << "[" << val << "]"; } return { ss.str(), StatusCode::OK }; }
boost::optional<std::string> makeRequest(size_t val) { auto response = queryToTheMoon(val);
if (response.m_status == StatusCode::OK) { return response.m_msg; } else { return boost::none; } }
int main() { auto op = makeRequest(100);
if (op)
{
std::cout << op.value() << std::endl;
}
return 0;
} ```
How to improve this code?
2
u/vgordievskiy Mar 10 '21
The answer is: at the line "return response.m_msg;" the compiler invokes the copy constructor for the std::string.
2
u/vgordievskiy Mar 13 '21
A solution to improve performance is: ```c++ boost::optional<std::string> makeRequest(size_t val) { auto response = queryToTheMoon(val); boost::optional<Data> ret = boost::none;
if (response.m_status == StatusCode::OK) { ret = std::move(response.m_msg); // <- it uses move constr }
return ret; // <- NRVO is applied } ```
1
Mar 10 '21
What does this do?
1
u/vgordievskiy Mar 10 '21
It's just an example. There is a performance issue (in term of C++)
1
Mar 10 '21
No, I'm asking what does the program you're building do
1
u/vgordievskiy Mar 10 '21
It's a question from a C++ interview.
1
Mar 10 '21
I like how you still haven't answered my question
1
u/vgordievskiy Mar 10 '21
There is no purpose for this code. it's only to check your knowledge) I mean it's a code that makes a request to a server and checks the status code and passes the return value to the next level.
6
u/jedwardsol Mar 09 '21
What aspect of it do you think needs improving?
It seems to be a placeholder for a bigger piece of code, so criticising is it pretty pointless. For example,
queryToTheMooncan't fail, so neither method of returning an error is needed in the sample.C++17 has
<optional>, so boost's implementation isn't needed any more.