This piece of code generates "error : Using object that is a temporary.".
#include<string>#include<vector>#include<sstream>inlinevoidMyStrCp(char*Dst,size_tDstSize,constchar*Src){#ifdef WIN32strcpy_s(Dst,DstSize,Src);#elsestrcpy(Dst,Src);#endif}classMyChannelInfo{public:MyChannelInfo(){}~MyChannelInfo(){deletem_name;}MyChannelInfo(constchar*name){m_name=newchar[strlen(name)+1];MyStrCp(m_name,strlen(name)+1,name);}MyChannelInfo&operator=(constMyChannelInfo&info){if(this!=&info){deletem_name;m_name=newchar[strlen(info.m_name)+1];MyStrCp(m_name,strlen(info.m_name)+1,info.m_name);}return*this;}MyChannelInfo(constMyChannelInfo&info){operator=(info);}inlineconstchar*GetName()const{returnm_name;}char*m_name=NULL;};typedefstd::vector<MyChannelInfo>MyChannelInfos;classMyChannel{public:MyChannel(){}std::stringGetComment(){std::stringstreamstr;str<<"My comment";returnstr.str();}};classFillVector{MyChannelInfos&channels;public:FillVector(MyChannelInfos&_channels):channels(_channels){}virtualvoidVisit1(MyChannel&channel){channels.push_back(MyChannelInfo(channel.GetComment().c_str()));}virtualvoidVisit2(){channels.push_back(MyChannelInfo("foo"));// reports error : Using object that is a temporary.}};
The tool seems lost, because it reports this error in Visit2, while it looks like Visit1 is actually causing problem: If I replace MyChannel::GetComment by:
However, retruning a std::string by copy in GetComment is perfectly OK (In my original code, the GetComment returns a string computed from other attributes of the class, no way to retrun a const reference). The string remains valid while MyChannelInfo constructor is called and char* copied to MyChannelInfo::m_name.
There should be no error here.
If you would like to refer to this comment somewhere else in this project, copy and paste the following link:
This piece of code generates "error : Using object that is a temporary.".
The tool seems lost, because it reports this error in Visit2, while it looks like Visit1 is actually causing problem: If I replace MyChannel::GetComment by:
Then the problem disappear...
However, retruning a std::string by copy in GetComment is perfectly OK (In my original code, the GetComment returns a string computed from other attributes of the class, no way to retrun a const reference). The string remains valid while MyChannelInfo constructor is called and char* copied to MyChannelInfo::m_name.
There should be no error here.
Greetings Jean. Would you be so kind to provide information about which cppcheck version was used with this example?
Thanks! I have created this ticket: https://trac.cppcheck.net/ticket/13244