Last updated:2026-10-12
STL string interview questions in depth¶
Today I am sharing a string-related interview question with a total of 4 cases. You can leave a comment in the discussion section saying what will happen in each of these four places.
Everyone should be quite familiar with std::string, and std::string_view is a view introduced after C++17 — look it up if you are not familiar with it. Below are two literals, a string literal and a string_view literal, represented by s and sv.
The first two questions both involve a function returning a std::string_view, but with a difference: one is based on a c-style string, the other on a string.
The last two questions involve construction from a string literal and a string_view literal.
Alright, the problem is now described clearly — see you in the comments~
std::string_view getBar() {
std::string b{"it is bar."};
return b;
}
std::string_view getFoo() {
return "It is foo.";
}
using namespace std::string_literals;
using namespace std::string_view_literals;
std::cout << getFoo() << std::endl; // 1
std::cout << getBar() << std::endl; // 2
std::string_view svf{"Hello foo"s};
std::cout << svf << std::endl; // 3
std::string_view svff{"Hello foo"sv};
std::cout << svff << std::endl; // 4
Related Topics¶
- STL array source code analysis | C++那些事
- STL string deep dive | C++那些事
- STL deque source code analysis | C++那些事
- STL empty base optimization EBO | C++那些事
- STL hand-written hash table implementation | C++那些事
- STL hashtable hash table | C++那些事
- STL iterator source code analysis | C++那些事
- STL list source code analysis | C++那些事
- STL map and multimap | C++那些事
- STL queue and stack source code analysis | C++那些事