c++ - If I pass a const char* to std::vector<std::string>'s push_back, will it be copied or moved? - Stack

In this code (using C++17), will "abc" be used to create a std::string temporary object and t

In this code (using C++17), will "abc" be used to create a std::string temporary object and then copied into letters by push_back, or will it be moved ?
Is it more efficient to use push_back or emplace_back in this circumstance?

#include <iostream>
#include <string>
#include <vector>
 
int main()
{
    std::vector<std::string> letters;
    letters.push_back("abc");
}

In this code (using C++17), will "abc" be used to create a std::string temporary object and then copied into letters by push_back, or will it be moved ?
Is it more efficient to use push_back or emplace_back in this circumstance?

#include <iostream>
#include <string>
#include <vector>
 
int main()
{
    std::vector<std::string> letters;
    letters.push_back("abc");
}
Share Improve this question edited Nov 18, 2024 at 11:56 wohlstad 30.4k17 gold badges61 silver badges94 bronze badges asked Nov 15, 2024 at 19:32 codeologycodeology 3573 silver badges12 bronze badges 3
  • 1 Literal constant strings are really arrays of (constant) characters, and usually stored in memory that is not writeable. This array itself can't be moved. But the temporary std::string object that is created in the call can be moved, but that string is independent of the literal string you pass as an argument. With that said, emplace_back is probably better anyway. – Some programmer dude Commented Nov 15, 2024 at 19:33
  • The foundation issue here is that a char-string literal needs to be converted to std::string before it can be put into the std::vector, because you declared a std::vector<std::string>. This conversion will take place first, then the new std::string will be placed into the std::vector. – Thomas Matthews Commented Nov 15, 2024 at 21:08
  • Beware sloppiness with the word "it". In your title, you ask "will [the const char*] be copied or moved?" while the question itself asks "will [the temporary object] be moved?" Those are two rather different questions. (For the former, moving a pointer is the same as copying it, so you probably meant the pointed-to data instead of the pointer. However, the copy of the data occurs when the temporary is created, so still before what is asked in the question's body.) – JaMiT Commented Nov 16, 2024 at 6:31
Add a comment  | 

1 Answer 1

Reset to default 5

vector::push_back() has an overload that accepts an rvalue, so the temporary std::string will be moved and not copied.

If you use vector::emplace_back() instead, the temporary std::string will be avoided altogether.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745674683a4639614.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信