Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

The codebase I'm currently working on has quite a few bugs related to ownership. However, the programmers I'm working with are very capable and all are familiar with different kinds of smart pointers in the STL. Unfortunately they are either, 1) typedef'd to the point where it's hard to tell what kind of ownership is used where, 2) often can't be used because objects need to be passed by reference to libraries that use regular-old-pointers.

I think many bugs could have been avoided by not typedef'ing our pointers, because when you have to type `std::shared_ptr<myclass>`, then you know what kind of pointer it is. On the other hand, if you have to, at least call the typedef `myclassSharedPtr` instead of `myclassPtr`. But for (2), I don't see a work-around. How can you write good code when your critical dependencies don't play nice?



> often can't be used because objects need to be passed by reference to libraries that use regular-old-pointers.

I don't understand what you mean by this. If you have a `smart_ptr<T> p;` nothing prevents you from passing `*p` or `p.get()` to some legacy interface. You only have trouble if that legacy interface wants to claim ownership of the object.


I think the issue is that the typedef is intended to hide the smartptrness so it's not obvious what the API for getting an old-style pointer is, or whether getting an old-style pointer is even part of the intended public interface anymore (beyond p.operator->() anyway ;)


> You only have trouble if that legacy interface wants to claim ownership of the object.

That's exactly what I mean. This happens. My point is just that even the best intentions are easily subverted in a real-world scenario where you didn't write the whole codebase yourself from scratch.


I agree on (1). Typedef obscures more than it helps.

On (2), I think the solution is intrusiveness. intrusive data structures and intrusive_ptr should be used more in C++.

The dislike for intrusiveness is rooted on equating classes with responsibilities. A single responsibility is often spread over several classes, because the classes form a useful cluster. A clear case is items of a collection. If an object already knows it's an item in a collection, there's really no harm in using intrusive lists.


Intrusiveness also isn't so good when you want the class logic to be independent of the memory management scheme in use. We experimented with language support for intrusive data structures in Rust (`@class` for an intrusive `shared_ptr`) and it turned out to be a lot of trouble, so we removed it.


Typedef should really be creating a new type, and not an alias. It's one of few thing I wish C(++) had different.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: