Unsafe Strings

What does the below C++ program do? #include <iostream> #include <memory> #include <string> void someFunction( const std::string& name ) { static const std::string* pCachedName = nullptr; if (pCachedName == nullptr) { pCachedName = &name; std::cout << "in someFunction set pCachedName to value: " << *pCachedName << std::endl; } else { std::cout << "in someFunction pCachedName has value: " << *pCachedName << std::endl; } } int main() { std::shared_ptr<std::string> name; name.reset(new std::string("alice")); std::cout << "before someFunction name = '" << *name << "'" << std::endl; someFunction(*name); name.reset(new std::string("bob")); someFunction(*name); std::cout << "after someFunction name = '" << *name << "'" << std::endl; return 0; } name is declared in main as a std::shared_ptr to a string. We pass name as a constant reference to someFunction assuming we do not need to worry about it being mutated or stored. ...

May 16, 2025 · 2 min · Aaron Riekenberg