简体   繁体   中英

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_back ing a char in the vector.

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
}

The advantage of (eg) std::vector‹T>::emplace_back is that it constructs an object of type T directly in the vector, instead of constructing a temporary and then copying it in.

Since char is a primitive type, there is no advantage in one method over the other, so there is no reason for std::string::emplace_back to exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM