最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论