Let's say I have a buffer of chars in memory that holds a c_string, and I want to add an object of std::string
with the content of that c_string to a standard container, such as std::list<std::string>
, in an efficient way.
Example:
#include <list>
#include <string>
int main()
{
std::list<std::string> list;
char c_string_buffer[] {"For example"};
list.push_back(c_string_buffer); // 1
list.emplace_back(c_string_buffer); // 2
list.push_back(std::move(std::string(c_string_buffer))); // 3
}
I use ReSharper C++, and it complains about #1 (and suggests #2).
When I read push_back vs emplace_back, it says that when it is not an rvalue, the container will store a "copied" copy, not a moved copy. Meaning, #2 does the same as #1. Don’t blindly prefer emplace_back to push_back also talks about that.
Case 3: When I read What's wrong with moving?, it says that what std::move()
does "is a cast to a rvalue reference, which may enable moving under some conditions".
--
Does #3 actually give any benefit? I assume that the constructor of std::string
is called and creates a std::string
object with the content of the c_string. I am not sure if later the container constructs another std::string
and copies the 1st object to the 2nd object.