变量 timeOld 在没有在 c++ 中初始化的情况下被使用

The variable timeOld is being used without being initialized in c++

本文关键字:情况下 初始化 timeOld c++ 变量      更新时间:2023-10-16
char* timeNew = _com_util::ConvertBSTRToString(cpi->getTime());
if(timeFirst == true)
    {
    strcpy(timeOld,timeNew);
    timeFirst = false;
    }

如果我不知道 CPI->getTime 返回的字符数组的大小是多少,我该如何启动 Timeold?

根据timeNew长度为其分配内存:

delete[] timeOld;
timeOld = new char[strlen(timeNew) + 1];

或者你可以timeOld做一个std::string,让它为你管理内存:

std::string timeOld;
timeOld = timeNew; // If timeNew is dynamically allocated you must still
                   // delete[] it when no longer required, as timeOld
                   // takes a copy of timeNew, not ownership of timeNew.

如果确实需要,您可以使用std::string::c_str()访问const char*

尽可能使用字符串:

char *t= _com_util::ConvertBSTRToString(cpi->getTime());
std::string timeNew(t);
delete[] t;
if(timeFirst == true)
{
     timeOld=timeNew;
     timeFirst = false;
 }

如果您不必简单地管理函数返回的内存:

std::string timeNew(_com_util::ConvertBSTRToString(cpi->getTime()));
if(timeFirst == true)
{
     timeOld=timeNew;
     timeFirst = false;
 }

如果你必须使用ConvertBSTRToString,那么使用boost::scoped_array<char>boost::shared_array<char>来确保你得到清理。

boost::shared_array<char> time;
time.reset( _com_util::ConvertBSTRtoString( cpi->getTime() );

自动重新分配。无需调用删除或删除[]。