我有我认为简单的代码 - 我想在QStringList中添加3个字符串.这是我的代码:
baseName = "qwerty";
QStringList *newBOMList;
for (auto ii = 0; ii <= 2; ii++)
{
if (ii == 0) {
newBOMList->append(baseName);
}else
if (ii == 1) {
newBOMList->append("A");
}else
if (ii == 2) {
newBOMList->append(baseName + " description");
}
}
Run Code Online (Sandbox Code Playgroud)
我在第一个追加行上收到编译器警告:
'newBOMList'可以在此函数中使用未初始化[-Wyybe-uninitialized] newBOMList-> append(baseName);
但不是其他两个.
这段代码是一个类的方法.
我喜欢至少理解警告,如果没有在我的项目中摆脱它们,但我真的不明白为什么会发生这种警告.
请问有什么线索吗?
另外,这是将3个字符串添加到QStringList的最佳方法吗?
哦 - 我在Linux机器上使用qt-creator - 如果这有任何区别的话.
您创建了一个指向QStringList的指针,但从未实际创建过该对象,因此指针未初始化.
QStringList *newBOMList; //pointer to nowhere, results in error/warning on use
QStringList *newBOMList = new QStringList(); //now you have an actual instance, remember to clear it up with "delete newBOMList "
QStringList newBOMList; //stack/local instance, no need to deallocate
Run Code Online (Sandbox Code Playgroud)
如果你需要一个动态分配的一个,身份证强烈建议寻找到std::unique_ptr,std::shared_ptr和类似的管理内存为您服务.他们负责释放没有明确分配的内存delete p.
例如,编辑你的origenal代码,这些将是选项:
//local/auto allocated
baseName = "qwerty";
QStringList localBOMList;
for (auto ii = 0; ii <= 2; ii++)
{
if (ii == 0) {
localBOMList.append(baseName);
}else
if (ii == 1) {
localBOMList.append("A");
}else
if (ii == 2) {
localBOMList.append(baseName + " description");
}
}
//dynamically allocated, but will be destroyed as soon as the unique_ptr object is so no need for "delete newBOMList" to prevent a memory leak
baseName = "qwerty";
std::unique_ptr<QStringList> newBOMList(new QStringList());
for (auto ii = 0; ii <= 2; ii++)
{
if (ii == 0) {
newBOMList->append(baseName);
}else
if (ii == 1) {
newBOMList->append("A");
}else
if (ii == 2) {
newBOMList->append(baseName + " description");
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
66 次 |
| 最近记录: |