简体   繁体   中英

C++ std::copy result different from string constructor

I've encountered some strange behaviour when using std::copy. With

std::vector<std::string> chosenIDs{...};
for (const auto& x : chosenIDs) {
  std::string strID("");
  std::copy(std::begin(x), std::find(std::begin(x), std::end(x), '.'), std::begin(strID));
  std::cout << strID << "\n";
}

the strID string contains characters it's not supposed to, however

std::vector<std::string> chosenIDs{...};
for (const auto& x : chosenIDs) {
  std::string strID(std::begin(x), std::find(std::begin(x), std::end(x), '.'));     
  std::cout << strID << "\n";
}

works completely fine. It's clear to me that I should be using the second approach, but it still baffles me as to why the behaviour in the first snippet is different from the second one.

I'm using GCC 5.4.0

When using std::copy() it is necessary to make sure that neither range makes out of bounds accesses. The target range starts out empty and there isn't anything done to expand it. Thus, the result is undefined behavior.

The problem can be fixed, eg, by using a destination iterator growing the target sequence:

std::copy(std::begin(x), std::end(x),
            std::back_inserter(strID));

As @MM said: The copy writes out of bounds of strID ( copy does not resize the destination). You could use std::back_inserter(strID) as the third argument instead. std::back_inserter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM