The following code encountered a segment fault with the const string& constructor, and exit with 0 with the string_view constructor. I know the const string& is not the best way to do so. But from my understanding, without optimization, a temp string is constructed from const char*, then it's value gets copied in the Person constructor before it gets destroyed. And the constructor looks valid to me. For the find part, the set::find (string_view) will use the defined less operators as needed. And I didn't see what's wrong here. I am able to reproduce the issue with g++-10 or VS2022.
#include <set>
#include <iostream>
#include <string>
#include <string_view>
using namespace std;
struct Person{
string name;
Person(const string& s):name{s}{}
//Person(string_view s):name{s}{}
bool operator<(string_view s)const{
return name<s;
}
bool operator<(const Person& o)const{
return name<o.name;
}
};
bool operator<(string_view s,const Person& p){
return s<p.name;
}
set<Person,less<>>s;
int main(){
s.emplace("hello");
string_view hel="hel";
auto res=s.find(hel);
}
gdb gives me the following information about the crash:
Program received signal SIGSEGV, Segmentation fault.
0x000000000800280c in std::char_traits<char>::copy (__s1=0x7fffff7ef1c0 "\340\361~\377\377\177", __s2=0x7fffff7ef230 "hello",
__n=<error reading variable: Cannot access memory at address 0x7fffff7eeff8>) at /usr/include/c++/10/bits/char_traits.h:401
401 copy(char_type* __s1, const char_type* __s2, size_t __n)
backtraceit's obvious.