Chris
Chris

Reputation: 75

C++ move semantics string

I am working on an embedded system and therefore it is not possible to throw exceptions, just to mention it. Therefore my return value will be a struct. I'm not sure if I have to call std::move on std::string. This below is a very reduced, simplified example.

// The response struct
struct Response_Param
{
  size_t status;
  std::string value;
};

Response_Param get_value()
{  
  std::string value = "Response value";
  size_t status{0};

  return {status, std::move(value)};
};

In the main code

Response_Param param_result = get_value();
if (0 == param_result.status) {
  std::string header_val = std::move(param_result.value);
  // do sth with header_val
  // [...]
}

Is it superfluous to call std::move in both cases? Or do I gain some performance benefits?

[EDIT] To make it more clearer why I want to use std::string in this example, I add a more elaborated get_value() function. This function should read a http header key-value pair:

/**
* @param key [in] The http header key to 
* look for. If found, the lib function 
* will fill up the char* raw ptr by this 
* value.
* @param max_len [in] The max_len of the  
* header value. If header value > max_len 
* returns a truncation status.
**/
Response_Param get_value(const char*key, const size_t max_len = 200)
{  
  std::string value;
  size_t status{0};

  status = get_hdr_key_val_lib(key, value.c_str(), max_len);

  return {status, std::move(value)};
};

Upvotes: 2

Views: 178

Answers (1)

Werner Henze
Werner Henze

Reputation: 16771

Normally I would advise to rewrite the function so that named return value optimization (NRVO) kicks in.

Response_Param get_value()
{  
  Response_Param result{ 0, "Response value" };

  return result;
}

But as you write that you get the value from a wrapped library function and need to copy it, that change does not help you much. So in your case you can get a performance benefit from using std::move for the string.

If you want to see the difference, then just run the program in a debugger, step through it and check when copies are made and when moves are made.

BTW, I doubt that your wrapping of get_hdr_key_val_lib is correct. You are passing value.c_str() as second parameter, but that it a const char* pointing to an empty string (as value has not been assigned any value). You probably meant to reserve some space first and then to pass value.data()?

Upvotes: 1

Related Questions