[英]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
?为什么没有
emplace
或emplace_back
为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.我认为这与
char
的使用无关,因为您可以拥有一个字符向量,并且在向量中使用emplace_back
一个字符没有问题。
There would be no gain over push_back
push_back
不会有任何好处
The power of emplace_back
is that it constructs an object in-place , where it is designed to stay. emplace_back
的强大之emplace_back
在于它就地构造了一个对象,它被设计为停留在那里。 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.对于
std::string
(或任何只能容纳原始类型的理论容器),增益是不存在的。 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
您可以使用文字或其他变量,但您必须在
push_back
和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. (eg)
std::vector‹T>::emplace_back
是它直接在向量中构造了一个 T 类型的对象,而不是构造一个临时对象然后再复制进去。
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.由于
char
是一种原始类型,因此一种方法与另一种方法相比没有优势,因此std::string::emplace_back
没有理由存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.