Last active
May 17, 2020 14:15
-
-
Save mp4096/584e72b6feb9f8bdfaf54ea777074466 to your computer and use it in GitHub Desktop.
Fun with lifetimes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
struct Foo { | |
float x; | |
float y; | |
float z; | |
}; | |
using Bar = std::vector<float>; | |
Foo MakeFoo(); | |
Bar MakeBar(); | |
std::ostream &operator<<(std::ostream &os, Foo const &data); | |
std::ostream &operator<<(std::ostream &os, Bar const &data); | |
template <typename T> class View { | |
public: | |
explicit View(T const &data) : ref_{data} {} | |
T const &GetRef() const { return ref_; } | |
private: | |
T const &ref_; | |
}; | |
Foo MakeFoo() { return Foo{1.0F, 2.0F, 3.0F}; } | |
Bar MakeBar() { return Bar{1.0F, 2.0F, 3.0F}; } | |
std::ostream &operator<<(std::ostream &os, Foo const &data) { | |
os << "x: " << data.x << ", y: " << data.y << ", z: " << data.z; | |
return os; | |
} | |
std::ostream &operator<<(std::ostream &os, Bar const &data) { | |
for (auto const &x : data) { | |
os << x << " "; | |
} | |
return os; | |
} | |
int main() { | |
// Correct: | |
// const Foo foo{MakeFoo()}; | |
// View<Foo> foo_view{foo}; | |
View<Foo> foo_view{MakeFoo()}; | |
std::cout << foo_view.GetRef() << std::endl; | |
// Correct: | |
// const Bar bar{MakeBar()}; | |
// View<Bar> bar_view{bar}; | |
View<Bar> bar_view{MakeBar()}; | |
std::cout << bar_view.GetRef() << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Compile and run with:
$ clang++-10 -std=c++14 foobar.cpp -Werror -Weverything -Wno-c++98-compat -O3 -g -fsanitize=address -fsanitize-address-use-after-scope -fsanitize-recover=address && ASAN_OPTIONS=halt_on_error=0 ./a.out
Play around with different opt levels.