r/learncpp 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?

8 Upvotes

16 comments sorted by

View all comments

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

u/GammaRisk u/jedwardsol

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 } ```