0

The code is :

std::vector<std::string*> itemDataList;
for(int i = 0 ; i<4; i++){
    ctr::ZwItem zwItem;
    zwItem.news = newsList[i];
    zwItem.__isset.news = true;

    boost::shared_ptr<TMemoryBuffer> buffer(new TMemoryBuffer());
    TCompactProtocol compactProtocol(buffer); 

    zwItem.write(&compactProtocol);
    std::string itemData = buffer->getBufferAsString();
    INFO << newsId << " size: " << std::to_string(itemData.size());
    itemDataList.emplace_back(&itemData);

}

std::ostringstream yy;
for(auto p : itemDataList){
    yy << std::to_string(p->size()) << ",";
}
MI << "sizeList: [" << yy.str() << "]";


and the running log shows this: enter image description here

when I print the serialized string sizes after the for loop, the 4 string pointers in itemDataList have the same size , not the expected [3033, 2581, 2938, 2458].

So what's the problem with my code?

L.Maple
  • 111
  • 3
  • 11
  • 1
    Scope and life-time! The life-time of the variable `itemData` ends with each iteration of the loop, and the object will be destructed. All pointers to the variable will immediately become invalid, and any attempt to dereference these pointers lead to *undefined behavior*. Don't store pointers to containers or strings. In your case, if you want to avoid a copy, *move* it instead (`idemDataList.emplace_back(std::move(itemData))`, assuming you "fix" the vector). – Some programmer dude Mar 23 '22 at 13:40
  • @Someprogrammerdude you are right, I fix it according to your answer, thanks. – L.Maple Mar 23 '22 at 14:47
  • Already explained neatly by @Someprogrammerdude, for an in depth treatment of the topic, you might appreciate this cppcon talk, https://www.youtube.com/watch?v=uQyT-5iWUow – Rajesh Mar 23 '22 at 15:04

0 Answers0