Search code examples
c++stringemplace

Why is there no emplace or emplace_back for std::string?


I'm pretty sure I've seen this asked on here before, but I can't seem to find the post when I tried searching, and I don't recall the answer.

Why is there no emplace or emplace_back for std::string?

I don't think it's related to the use of char, since you can have a vector of chars, and there's no problem with emplace_backing a char in the vector.


Solution

  • There would be no gain over push_back

    The power of emplace_back is that it constructs an object in-place, where it is designed to stay. No copies or moves are needed. And it also provides simpler syntax for creating objects, but that's just a minor advantage.

    class Person
    {
        std::string name;
        int age;
        double salary;
    }
    
    int main()
    {
        std::vector<Person> people;
        people.push_back(Person{"Smith", 42, 10000.0}); //temporary object is needed, which is moved to storage
        people.emplace_back("Smith", 42, 10000.0); //no temporary object and concise syntax
    }
    

    For std::string (or any theoretical container that can only hold primitive types), the gain is nonexistent. No matter if you construct object in place or move it or copy it, you perform the same operation at assembly level - write some bytes at given memory.
    Syntax also cannot become more concise than it is - there is no constructor that needs to be called. You can use a literal or another variable, but you have to do exactly same thing in both push_back and emplace_back

    int main()
    {
        std::vector<char> letters;
        letters.push_back('a');
        letters.emplace_back('a'); //no difference
    }