Category : lifetime

Consider this snippet: #include <iostream> #include <string> #include <string_view> using namespace std::literals; class A { public: std::string to_string() const noexcept { return "hey"; // "hey"s } std::string_view to_stringview() const noexcept { return "hello"; // "hello"sv } }; int main() { A a; std::cout << "The class says: " << a.to_string() << ‘n’; std::cout << "The ..

Read more

We can sometimes write code like the following. When bad returns, std::string("bad") is destroyed, and I can’t actually use bad_char or print_str(s). #include <string> #include <stdio.h> const char* bad(){ return std::string("bad").c_str(); } void print_str(const char* s){ printf("%s", s); } int main(){ const char* bad_char = bad(); print_str(bad_char); } However, compilers can’t detect such error at ..

Read more

Put it other way, conversely, are std::span iterators invalidated after the span instance is destroyed? I have a vector I need to iterate over with different layouts. I’m trying to make use of std::span to avoid writing a lot of iterator boilerplate or bringing in an external library dependency. Simplified example: #include <iostream> #include <span> ..

Read more

I am learning c++ and try to understand the object lifetime of the move constructor and copy constructor. I am using g++ 9.2.0, c++17 in vscode. When I wrote the following code for a card game, the output confuses me so much… #include <iostream> #include <string> #include <vector> #include <utility> #include <algorithm> static const std::vector<std::string> ..

Read more

Most likely there is a duplicate someone can point me to… #include <iostream> #include <typeinfo> class A {}; A f() { return A(); } int main() { auto &&a = f(); std::cout << typeid(f()).name() << std::endl; std::cout << typeid(a).name() << std::endl; std::cout << typeid(A()).name() << std::endl; return 0; } It outputs 1A 1A F1AvE Questions ..

Read more