Suat Mutlu
Suat Mutlu

Reputation: 237

Why is the move constructor not called when initializing std::vector with const char literals?

I understand that when initialization occurs with rvalues, the move constructor should be called if it is implemented. Therefore, I expected the move constructor to be called for the following code with the compiler options "-fno-elide-constructors -Qn" (for the purpose of disable copy elision):

std::vector<std::string> my_vec {"hello", "world"};

However, copy constructors are being called for "hello" and "world". Why is this happening?

Best regards.

Upvotes: 0

Views: 95

Answers (1)

Roman Leshchuk
Roman Leshchuk

Reputation: 331

In this code, you are trying to create std::vector from std::initializer_list. std::initializer_list container gives access to its elements only by const references or pointers to const values. For this reason, you can not use move semantics, because you can not move from const value, because then you will need to assign default value, what is impossible here (because const is not modifiable). So you need to create copies of given strings. You will meet the same behaviour while using std::set, std::map and other associative containers with key of type const T.

Upvotes: 1

Related Questions