Vector initialization with std :: begin and std :: end

Why is it working? There are two different lines of "testString" , but the size of the vector is allocated correctly.

 #include <iostream> #include <vector> #include <iterator> int main() { std::vector<char> str; str.assign(std::begin("testString"), std::end("testString")); copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout, " ")); std::cout<<str.size(); return 1; } 
+5
source share
4 answers

You are lucky, and the compiler has optimized the pools . Please note that everything you do is still undefined, and with a different compiler or different compiler settings, you're out of luck. Do not do it again.

+9
source

Two identical lines of letters are most likely combined into one in memory, so that the beginning and end refer to the same line.

This only works "randomly" in your program, though ...

It is somewhat related. How C ++ compilers combine identical string literals

+2
source

Since the compiler is allowed to store the same string literal that is used elsewhere in one place, it is more than likely that both std::begin("testString") and std::end("testString") actually refer to the same same line.

This is not required to be done by standard, and the compiler can store both of these string literals in different places that would violate this code. Just because it works doesn’t mean you should do it. I would suggest using

 std::vector<char> str; const char [] chstr = "testString" str.assign(std::begin(chstr), std::end(chstr)); 

Or better yet

 std::string str = "testString"; copy(str.begin(), str.end(), std::ostream_iterator<char>(std::cout, " ")); 
+2
source

There are two different lines: "testString"

They are the same in your case. The compiler is allowed to combine storage for equal or overlapping string literals .

The compiler is allowed but not required to combine storage for equal or overlapping string literals. This means that identical string literals may or may not be compared when compared by pointer.

You can check it out,

 std::cout << std::boolalpha << ("testString"=="testString"); 

Live

In any case, you should not depend on this, the behavior is not guaranteed.

+2
source

Source: https://habr.com/ru/post/1243855/


All Articles