变量 timeOld 在没有在 c++ 中初始化的情况下被使用
The variable timeOld is being used without being initialized in c++
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() );
自动重新分配。无需调用删除或删除[]。
相关文章:
- 如何在不知道属性具有哪些构造函数的情况下初始化属性?
- 在没有库的情况下初始化 OpenGL
- 在没有构造函数的情况下初始化 const c++ 类
- 默认情况下初始化时 POD 是否给予特殊处理 (C++14)?
- 为什么默认情况下初始化局部变量
- 有没有一种方法可以在不使用std ::移动的情况下初始化类构建类的类
- 如果在没有 new 运算符的情况下初始化,C++是否将类对象视为值类型
- 如何在没有循环的情况下初始化 std::vector
- 如何在不使用指针的情况下初始化具有可变大小的 2D 数组
- 如何在给定包含类的实例的情况下实例化嵌套类
- 在不使用"new"的情况下实例化参数参数中的对象
- 在不使用动态数组的情况下初始化数组时出现问题
- 如何在没有初始化对象的情况下初始化对象的管理器shared_ptr?
- 在没有 new 关键字的情况下初始化C++对象的内存从何而来
- 如何在没有main的情况下初始化谷歌测试
- 在下面的代码中,如何在不使用伪值的情况下初始化类成员
- 如何在不使用C++11功能的情况下初始化类中的数组
- 如何在<int>没有循环的情况下初始化值为 {1,1,1,...,1} 的向量 v(1000)C++?
- 在没有实例变量的情况下初始化派生类中的"inherited static members"
- wxWidgets:如何在不使用宏和不进入主应用程序循环的情况下初始化wxApp