使用static_cast <void>忽略迭代器作为返回值是否正确?

问题描述

我必须处理来自std::remove的[[nodiscard]]警告;

static_cast<void>(std::remove(stringVar.begin(),stringVar.end(),' '));

我想要正确的方法。可以通过以下代码停止警告:

auto temp = std::remove(stringVar.begin(),' ');

我不想使用std::remove的返回值。

void main()
{
    std::string stringVar { "Operation : In,Value : 3884," };

    size_t from = 0,to = 0,pos = 0;
    std::string delFrom{ ":" },delTo{ "," };

    static_cast<void>(std::remove(stringVar.begin(),' '));

    from = stringVar.find(delFrom,pos);
    to = stringVar.find(delTo,pos);
    std::cout<< stringVar.substr(from + 1,to - from - 1);
}

输出

In

这是一个特定的问题,对已经在SO上搜索过的问题不感兴趣。

更新:数据一致且可读的格式。

解决方法

这里的问题是,如果您不使用temp,则不会正确删除字符串中的空格。

正确的代码是

auto temp = std::remove(stringVar.begin(),stringVar.end(),' ')
stringVar.erase(temp,stringVar.end());

您看到std::remove不会从任何内容中删除任何内容(当它只有两个迭代器时怎么办?)。它所做的只是重新排列字符串,以使字符串末尾的项目成为应该擦除的字符串的一部分(您可以将其视为将所有空格都移到字符串末尾,但实际上比)。

要真正擦除,您需要使用string::erase返回的迭代器来调用std::remove,如上面的代码所示。

,

正如@john指出的那样,如果您放弃该值,则该操作将无效。这就是[[nodiscard]]说明符的全部要点,该说明符防止防止用户忽略其值。


如果您有充分的理由忽略警告,那么您已经建议的方法是执行此操作的最佳方法。将其转换为void

static_cast < void >

如果您想使用宏

#define ignore(x) (static_cast < void > (x))

了解更多:How can I intentionally discard a no-discard return value?