调用已被std::move的std::basic_string对象的find方法是否合法?
std::basic_string::find on a moved-from std::string? Great question! Let's break this down clearly, since understanding moved-from object states and member function preconditions is key here.
First, let's recap what "valid but unspecified state" means for a moved-from std::string:
- The object remains in a legally valid state—all its internal rules (invariants) are intact: no dangling pointers, consistent size/capacity values, etc.
- You can safely call any member function that has no extra preconditions beyond the object being valid. The catch? The function's result might be unpredictable, since the object's actual content (like its characters) isn't defined.
Now, what about std::basic_string::find? Does it have any preconditions we need to worry about?
Looking at the C++ standard, find has no explicit preconditions for the calling std::string object itself. The only requirements tie to the arguments you pass (e.g., the C-style search string can't be a null pointer). As long as the string is in a valid state (which a moved-from string definitely is), calling find is 100% safe—it won't trigger undefined behavior.
Let's look at your code example:
#include <string> int main() { std::string str = "hello"; auto s = std::move(str); str.find("world"); }
This code is perfectly legal. After moving from str, it's left in that valid-but-unspecified state. Calling str.find("world") won't crash or cause UB, but you can't predict what the return value will be—it might be std::string::npos (if the unspecified content doesn't include "world"), or some random index (if it happens to contain the substring by coincidence). The behavior is defined, just not predictable.
To wrap up:
- Yes, you absolutely can call
std::basic_string::findon a moved-fromstd::string. findhas no preconditions that a moved-from string violates.- The only caveat is that the result of the
findcall will be unpredictable, since the string's content is unspecified.
内容的提问来源于stack exchange,提问作者wanwan

