If my understanding of try_emplace is correct, it doesn't move rvalue arguments in case of insertion failure.
Unlike insert or emplace, these functions do not move from rvalue arguments if the insertion does not happen, which makes it easy to manipulate maps whose values are move-only types, such as std::map<std::string, std::unique_ptr<foo>>. https://en.cppreference.com/w/cpp/container/map/try_emplace
Cppcheck reports "Access of moved variable" when I try to access std::unique_ptr in case of failure of the try_emplace.
Code example:
#include<iostream>#include<map>#include<memory>#include<stdint.h>intmain(void){std::map<uint32_t,std::unique_ptr<uint32_t>>m_map;autoreq1=std::make_unique<uint32_t>(321);autoreq2=std::make_unique<uint32_t>(4321);auto[it1,result1]=m_map.try_emplace(123,std::move(req1));if(result1!=true){std::cout<<"Failed to insert map, req1="<<*req1<<"\n";return1;}std::cout<<"Insertion OK, req1="<<*it1->second<<"\n";auto[it2,result2]=m_map.try_emplace(123,std::move(req2));if(result2!=true){std::cout<<"Failed to insert map, req2="<<*req2<<"\n";return1;}std::cout<<"Insertion OK, req2="<<*it2->second<<"\n";return0;}
Code compiling and running: g++ -std=c++20 test.cpp -o test && ./test
Checkingtest.cpp...test.cpp:16:56:warning:Accessofmovedvariable'req1'.[accessMoved]std::cout<<"Failed to insert map, req1="<<*req1<<"\n";^test.cpp:13:50:note:Callingstd::move(req1)auto[it1, result1]=m_map.try_emplace(123,std::move(req1));^test.cpp:16:56:note:Accessofmovedvariable'req1'.std::cout<<"Failed to insert map, req1="<<*req1<<"\n";^test.cpp:25:56:warning:Accessofmovedvariable'req2'.[accessMoved]std::cout<<"Failed to insert map, req2="<<*req2<<"\n";^test.cpp:22:50:note:Callingstd::move(req2)auto[it2, result2]=m_map.try_emplace(123,std::move(req2));^test.cpp:25:56:note:Accessofmovedvariable'req2'.std::cout<<"Failed to insert map, req2="<<*req2<<"\n";
If I replace try_emplace with insert, I get segmentation fault.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
If my understanding of
try_emplaceis correct, it doesn't move rvalue arguments in case of insertion failure.Cppcheck reports "Access of moved variable" when I try to access
std::unique_ptrin case of failure of thetry_emplace.Code example:
Code compiling and running:
g++ -std=c++20 test.cpp -o test && ./testCppcheck command:
cppcheck test.cpp --std=c++20 --enable=all --addon=threadsafety.py --inline-suppr --suppress=missingIncludeSystemCppcheck output:
If I replace
try_emplacewithinsert, I get segmentation fault.Covered by https://trac.cppcheck.net/ticket/12773