Is it right to use static_cast<void> to ignore iterator as return value?

300 Views Asked by At

I have to handle the [[nodiscard]] warning from std::remove;

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

I want the correct way to do it. The warning can be stopped by below code:

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

I dont want to use the return value of 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(), stringVar.end(), ' '));

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

Output:

In

This is a specific question do not interested in already searched question on SO.

Update: Data consistent and readable format.

2

There are 2 best solutions below

6
john On BEST ANSWER

The problem here is that if you don't use temp you haven't properly removed the spaces from your string.

The correct code is

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

You see std::remove does not remove anything from anything (how can it when all it has are two iterators?). All it does is rearrange the string so that the items at the end of the string are the part of the string that should be erased (you can think of it as moving all the spaces to the end of the string but actually it's more complicated than that).

To actually erase you need to call string::erase, using the iterator returned by std::remove as the code above shows.

0
AudioBubble On

As pointed out by @john, the operation won't work if you discard the value. That is the whole point of the [[nodiscard]] specifier which is to prevent the user from ignoring its value.


If you have a good reason to ignore the warning, the method you already suggest is the best way to do this. Which is to cast it to void.

static_cast < void >

If you wanna use a macro

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

Read more: How can I intentionally discard a no-discard return value?