diff options
author | Andy Belle-Isle <drumsetmonkey@gmail.com> | 2019-08-30 00:19:31 -0400 |
---|---|---|
committer | Andy Belle-Isle <drumsetmonkey@gmail.com> | 2019-08-30 00:19:31 -0400 |
commit | bd3fe0cac583739bc0d7c4b5c8f301bb350abca0 (patch) | |
tree | 7eeb1aabcebd6999de1c3457d0882246ec0ff4d4 /deps/sol2/examples/source/tutorials/pointer_lifetime.cpp | |
parent | 2662ac356ce14dacfbc91689fd37244facff4989 (diff) |
Renamed lib to deps so github will ignore it for language stats
Diffstat (limited to 'deps/sol2/examples/source/tutorials/pointer_lifetime.cpp')
-rw-r--r-- | deps/sol2/examples/source/tutorials/pointer_lifetime.cpp | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/deps/sol2/examples/source/tutorials/pointer_lifetime.cpp b/deps/sol2/examples/source/tutorials/pointer_lifetime.cpp new file mode 100644 index 0000000..84bc536 --- /dev/null +++ b/deps/sol2/examples/source/tutorials/pointer_lifetime.cpp @@ -0,0 +1,75 @@ +#define SOL_ALL_SAFETIES_ON 1
+#include <sol/sol.hpp>
+
+struct my_type {
+ void stuff() {
+ }
+};
+
+int main () {
+
+ sol::state lua;
+
+ /*
+ // AAAHHH BAD
+ // dangling pointer!
+ lua["my_func"] = []() -> my_type* { return new my_type(); };
+
+ // AAAHHH!
+ lua.set("something", new my_type());
+
+ // AAAAAAHHH!!!
+ lua["something_else"] = new my_type();
+ */
+
+ // :ok:
+ lua["my_func0"] = []() -> std::unique_ptr<my_type> { return std::make_unique<my_type>(); };
+
+ // :ok:
+ lua["my_func1"] = []() -> std::shared_ptr<my_type> { return std::make_shared<my_type>(); };
+
+ // :ok:
+ lua["my_func2"] = []() -> my_type { return my_type(); };
+
+ // :ok:
+ lua.set("something", std::unique_ptr<my_type>(new my_type()));
+
+ std::shared_ptr<my_type> my_shared = std::make_shared<my_type>();
+ // :ok:
+ lua.set("something_else", my_shared);
+
+ // :ok:
+ auto my_unique = std::make_unique<my_type>();
+ lua["other_thing"] = std::move(my_unique);
+
+ // :ok:
+ lua["my_func5"] = []() -> my_type* {
+ static my_type mt;
+ return &mt;
+ };
+
+ // THIS IS STILL BAD DON'T DO IT AAAHHH BAD
+ // return a unique_ptr that's empty instead
+ // or be explicit!
+ lua["my_func6"] = []() -> my_type* { return nullptr; };
+
+ // :ok:
+ lua["my_func7"] = []() -> std::nullptr_t { return nullptr; };
+
+ // :ok:
+ lua["my_func8"] = []() -> std::unique_ptr<my_type> {
+ // default-constructs as a nullptr,
+ // gets pushed as nil to Lua
+ return std::unique_ptr<my_type>();
+ // same happens for std::shared_ptr
+ };
+
+ // Acceptable, it will set 'something' to nil
+ // (and delete it on next GC if there's no more references)
+ lua.set("something", nullptr);
+
+ // Also fine
+ lua["something_else"] = nullptr;
+
+ return 0;
+}
|