Home > OS >  Is it ok to call std::basic_string::find on already moved string?
Is it ok to call std::basic_string::find on already moved string?

Time:04-10

According to std::move, a moved std::string is in a "valid but unspecified state", which means that functions without preconditions can be used on the string. Is it ok to use std::basic_string::find on the unspecified string? Does std::basic_string:find have any precondition?

#include <string>
int main() {
  std::string str = "hello";
  auto s = std::move(str);
  str.find("world");
}

CodePudding user response:

According to the description of std::basic_string:find in [string.find]:

constexpr size_type F(const charT* s, size_type pos) const;

has effects equivalent to: return F(basic_­string_­view<charT, traits>(s), pos);

which has the following effects

Effects: Let G be the name of the function. Equivalent to:

basic_string_view<charT, traits> s = *this, sv = t; 
return s.G(sv, pos);

which will construct basic_string_view from *this, which has preconditions that [str, str len) is a valid range, and since the moved string is still in a valid state, so this is OK.

  •  Tags:  
  • c
  • Related