3 ms·
At least you can express ownership semantics in C++ code, using constructs like `unique_ptr`, `scoped_ptr`, and `shared_ptr`. In a garbage collected language,
by jemfinch 15y ago
At least you can express ownership semantics in C++ code, using constructs like `unique_ptr`, `scoped_ptr`, and `shared_ptr`. In a garbage collected language, nothing expresses ownership, and so while you not be at risk of memory leaks, you're still vulnerable to all the other bugs that come with aliasing mutable objects.
The "framework issue" you describe is solved precisely by specifying ownership semantics in terms of smart pointer return values. The way everyone becomes "100% sure what that return means" is by whether it returns a `unique_ptr` or a `shared_ptr`. The OP is simply complaining that `auto` takes away that local information on ownership.
`operator new()` is only trivial by virtue of not specifying anything at all about ownership. `scoped_ptr` and `shared_ptr` and `unique_ptr` are each specifying different, more restricted, but still trivial ownership semantics. They aren't "deep C++ voodoo" in the least. Your post smacks of someone who doesn't actually write C++ for a living.
- oconnore 15y ago> In a garbage collected language, nothing expresses ownership, and so while you not be at risk of memory leaks, you're still vulnerable to all the other bugs that come with aliasing mutable objects. You are conflating required language features with proper API design and documentation. I don't need '(unique|scoped|shared)_ptr' to refrain from aliasing mutable types, or to document my code properly on the rare occasion when I am required to.
- cpeterso 15y agoI wish C++11 added syntactic sugar for the smart pointer classes like scoped_ptr, shared_ptr, and unique_ptr. I would rather see new operators (like Microsoft C++/CLI's ^ and %) than even more templated code. Compare something like: int^ foo(int% bar); versus: std::unique_ptr<int> foo(std::shared_ptr<int> bar); Smart pointers have long been available in boost and are required for writing safe code, but they make code unreadable (even after typedefs).
- pyrtsa 15y agoI don't think introducing more syntax to the language for a feature that ultimately is a library solution, is a sustainable way to go. But if you really need a compact notation for smart pointers, you'll get pretty close by using template aliases, e.g. template <typename T> using up = std::unique_ptr<T>; template <typename T> using sp = std::shared_ptr<T>; // ... up<int> foo(sp<int> bar) { return bar ? up<int>(new int(*bar)) : nullptr; }
- thwest 15y agoOh C++11 has template typedefs? Time to migrate my project.