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 Answer
Reset to default 5vector::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.
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:33std::string
before it can be put into thestd::vector
, because you declared astd::vector<std::string>
. This conversion will take place first, then the newstd::string
will be placed into thestd::vector
. – Thomas Matthews Commented Nov 15, 2024 at 21:08const 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