简体   繁体   中英

what does C++ string erase return *this mean?

So the C++ string function

string& erase ( size_t pos = 0, size_t n = npos )

returns *this . What does that mean? Why do I need it to return anything?

Example

string name = "jimmy";  
name.erase(0,1);

will erase j and become immy , but why do I need it to return anything at all?

For method chaining . For example, after you erase, you can call == on it to check something:

string name = "jimmy";
bool b = name.erase(0,1) == "immy";

这只是为了方便,例如你可以链接这样的调用:

name.erase(0,1).erase(3,1);

In your example you don't need it to return anything, because the expression:

name.erase(0,1)

is equivalent to:

((void)name.erase(0,1), name)

So for example you could write:

while(name.erase(0,1).size()) {
    std::cout << name << '\n';
}

or:

while((name.erase(0,1), name).size()) {
    std::cout << name << '\n';
}

or:

while(name.erase(0,1), name.size()) {
    std::cout << name << '\n';
} 

or:

while(true) {
    name.erase(0,1);
    if (!name.size()) break;
    std::cout << name << '\n';
}

The standard has decided to give you the choice, probably on the basis that it might as well use the return value for something rather than "waste" it.

Basically, it sometimes saves a little bit of code that repeats a variable name or takes a reference to an intermediate result.

Some people think that functions that modify the object they're called on should not return anything (the idea being to limit the use of functions with side-effects to one per statement). In C++ they just have to live with the fact that the designers of the standard library disagree.

You can do things like this:

void process(std::string const &s) {}

process(name.erase(0,1)); //self-explanatory?

std::cout << name.erase(0,1) << std::endl; 

//etc

And things which the other answers has mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM