Skip to content

Instantly share code, notes, and snippets.

@mp4096
Last active May 17, 2020 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mp4096/584e72b6feb9f8bdfaf54ea777074466 to your computer and use it in GitHub Desktop.
Save mp4096/584e72b6feb9f8bdfaf54ea777074466 to your computer and use it in GitHub Desktop.
Fun with lifetimes
#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;
}
@mp4096
Copy link
Author

mp4096 commented May 17, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment