Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
What are some of the main reasons to use raw pointers in 2014, given that the C++11 standard is now well supported by most decent compilers?
I identified a couple of scenarios :
You are extending a legacy codebase that makes heavy use of raw pointers, and you would like to maintain consistency in style.
You are using a library that only exports raw pointers, but I guess you could still make use of casts.
You want to exploit pointers's capability to provide multiple levels of indirection. (I do not know C++11 well enough to know if this can be achieved using smart pointers, or using some other techniques.)
What other scenarios do you think are appropriate for use of pointers?
Would you even recommending learning about pointers in general, today?
I can imagine circumstances where you have a statically-allocated array and you want to use a raw pointer to iterate through it in high-performance code. There's still nothing wrong with this.
Your #1 is true.
Your #2 is possibly not right: if you're "making use of casts" to transform raw pointers owned by a third-party library, into smart pointers (implying local ownership) then something has gone horribly wrong.
Your #3 is technically true but avoid this whenever you can.
What is not recommended nowadays is playing with raw pointers to your own, dynamically-allocated memory. That is, the advice is to avoid new without smart pointers (and the corollary is that you shouldn't need delete).
Everybody is against raw pointers as it's way too easy to leak them.
But you can use raw pointers to point to data owned somewhere else... just don't new/delete them. Use std::unique_ptr or std::shared_ptr for that. Or for dumb (POD) memory buffers use std::vector<unsigned char>, don't malloc and free yourself.
Think of a std::vector<heavy_object*> when you need to juggle with sub-selections of objects that are non-trivial to copy but already exist elsewhere. You need pointers for this.
You also need pointers in functions for optional arguments where references don't cut it as you want to be able to pass a nullptr.
Pointers to consecutive objects can also be iterated easily without any std::iterator overhead. Just ++ or -- and that's it. I often use direct pointer iteration instead of begin, end for vectors.
As you understand how they work... you'll need them a lot and you'll use them properly.
Smart pointers are used for handling object ownership issues, but not all pointers are used to deal with object ownership. For example it makes more sense to pass raw pointer to a function if you are not planning to pass ownership to this function (i.e. you just want the function to deal with the data addressed by the pointer)
IMHO Raw pointers still have their place.
What C++11 gives us is the ability to manage the lifespan of raw pointers so that we don't have to delete them ourselves.
There is nothing wrong with using raw pointers as long as they are managed by a smart pointer/pointer manager in the correct scope or frame to ensure their lifespan is correct. If that is true then you never have to delete a raw pointer and you can safely use them within the scope/frame throughout which their life-time is guaranteed.
I would say, if possible, store a raw pointer to your new object in a std::unique_ptr if its lifespan should be controlled by a given scope/frame. Once that is done use the raw pointer within that scope frame. Just never delete it;
Sometimes it is not possible to manage the lifespan of a new object from a single scope or frame. In this case use a std::shared_ptr in every scope/frame that independently needs to manage the lifespan of the new object. Then, within each scope/frame, there is no reason not to use the raw-pointer just like when it is being managed by a std::unique_ptr.
So there is often no reason to incur the speed disadvantage of smart pointers as one of their strengths lies in managing the life-span of the new object in order to ensure the validity of the raw-pointer and the automatic destruction of its object when its no longer needed.
There are other times when a raw pointer is not appropriate.
For example when a managed pointer needs to transfer "ownership" to another scope/frame. That is when you need the scope/frame responsible for managing the life-span of the new object to change. In these cases avoid raw pointers like the plague!
What other scenarios do you think are appropriate for use of pointers?
One of the main scenarios in which raw pointers are used is when you have non-owning pointers. Typically, where a reference would work, but you want to avoid the constraints of a reference (non-reseatable, non-copyable). You could use a reference_wrapper type in those cases, but it's simpler to just use a raw pointer instead. Smart-pointers encode ownership (who creates and destroys the object), so, if there is no ownership to encode (because it is implied otherwise), then a raw pointer is OK.
Just to make it clear, typical examples of what I just explained are things like:
temporary copyable functors that need a pointer to some object that it doesn't own.
internal cross-links within a data structure (e.g., "back pointers").
But it's important to notice that these things should not, in general, be present in interfaces. Generally, you can avoid raw pointers pretty much completely in interfaces (e.g., library functions and classes), and only really use them internally, i.e., in library-side code, not in user-side code. In other words, if you need to use raw pointers, hide them away.
Raw pointers are also sometimes seen for optional function parameters, where you can pass in a nullptr if you don't want that result.
The main thing that should be avoided, and can be avoided in general, is naked new / delete calls in user-side code. A typical good modern C++ library (and even more so with C++11) will not have any such naked new / delete occurrences, and that's a fact.
Raw pointers are not so much a problem by themselves, what is problematic is (1) manual memory management, and (2) ownership management (which is problematic if raw pointers are used instead of smart-pointers).
Would you even recommending learning about pointers in general, today?
Of course you should learn about pointers. They are essential to understanding programming, and to learning to write library-side code. Raw pointers are still very present in the guts of a lot of library code and such, even if you don't see them.
common reasons to use raw pointers off the top of my head.
Reading and parsing binary files
Interacting directly with hardware
Arrays?
Speed. AFAIK Smart pointers are slower than raw pointers and there are relatively safe ways to use raw pointers. See Chromium's code base for example or WebKit's. Both use various kinds of tracked memory without the full overhead of smart pointers. Of course with limitations as well.
I think I have a considerable experience with normal (functional) designed patters, as described e.g. in the gang of four book, which I mainly used in java and C#. In these "managed" languages this is pretty much everything you need to know to get your work done.
However, in C++ world the developer also has the control of how all the objects get allocated, passed around and deleted. I understand the principles (I read Stroutrup among other texts), but it still takes me a lot of effort to decide which mechanism is best for a given scenario - and this is where a portfolio of memory-related design patterns would be useful.
For example, yesterday I had to create a class Results, that was a container for a few objects and a collection (std::vector in this case) of yet another type of objects. So there are a few design questions I couldn't really answer:
Should I return this class by value, or by smart pointer?
Inside the class, should the vector and the objects be normal members, or should they be stored as smart pointers again?
In the vector, should I store the objects directly, or smart pointers to them again?
What should the getters defined on my Results class return (i.e. values, references or smart pointers)?
Of course, smart pointers are cool and what not, but they create syntactic clutter and I am not convinced if using malloc for every single object is optimal approach.
I would be grateful for answers for the specific points above, but even more for some longer and more general texts on memory-related design patterns - so that I can solve the problems I will have on Mondays as well!
The answer to all of your questions ends up being one and the same: it depends on whether you need reference semantics or value semantics (with some caveats to be taken into account).
If you need reference semantics, which is what you have by default in languages like Java and C# for UDTs (User-defined Data Types) declared with the class keyword, then you will have to go for smart pointers. In this scenario you want several clients to hold safe aliases to a specific object, where the word safe encapsulates these two requirements:
Avoid dangling references, so that you won't try to access an object that doesn't exist anymore;
Avoid objects which outlive all of the references to them, so that you won't leak memory.
This is what smart pointers do. If you need reference semantics (and if your algorithms are not such to make the overhead of reference counting significant where shared ownership is needed), then you should use smart pointers.
You do need reference semantics, for instance, when you want the same object to be part of several collections. When you update the object in one collection, you want the representations of the same object in all the other collections to be consistently updated. In this case, you store smart pointers to your objects in those collections. Smart pointers encapsulate the identity of an object rather than its value.
But if you do not need to create aliases, then value semantics is probably what you should rely on. This is what you get by default in C++ when you declare an object with automatic storage (i.e. on the stack).
One thing to consider is that STL collections store values, so if you have a vector<T>, then copies of T will be stored in your vector. Always supposing that you do not need reference semantics, this might become anyway an overhead if your objects are big and expensive to copy around.
To limit the likelyhood of this scenario, C++11 comes with move operations, which make it possible to efficiently transfer objects by value when the old copy of the object is no more needed.
I will now try to use the above concepts to answer your questions more directly.
1) Should I return this class by value, or by smart pointer?
It depends on whether you need reference semantics or not. What does the function do with that object? Is the object returned by that function supposed to be shared by many clients? If so, then by smart pointer. If not, is it possible to define an efficient move operation (this is almost always the case)? If so, then by value. If not, by smart pointer.
2) Inside the class, should the vector and the objects be normal members, or should they be stored as smart pointers again?
Most likely as normal members, since vectors are usually meant to be conceptually a part of your object, and their lifetime is therefore bound to the lifetime of the object that embeds them. You rarely want reference semantics in such a scenario, but if you do, then use smart pointers.
3) In the vector, should I store the objects directly, or smart pointers to them again?
Same answer as for point 1): do you need to share those objects? Are you supposed to store aliases to those objects? Do you want changes to those objects to be seen in different parts of your code which refer those objects? If so, then use shared pointers. If not, is it possible to efficiently copy and/or move those objects? If so (most of the time), store values. If not, store smart pointers.
4) What should the getters defined on my Results class return (i.e. values, references or smart pointers)?
Same answer as for point 2): it depends on what you plan to do with the returned objects: do you want them to be shared by many parts of your code? If so, return a smart pointer. If they shall be exclusively owned by just one part, return by value, unless moving/copying those objects is too expensive or not allowed at all (quite unlikely). In that case, return a smart pointer.
As a side note, please be aware that smart pointers in C++ are a bit trickier than Java/C# references: first of all, you have two main flavors of smart pointers depending on whether shared ownership (shared_ptr) or unique ownership (unique_ptr) is desired. Secondly, you need to avoid circular references of shared_ptr, which would create islands of objects that keep each other alive even though they are no more reachable by your running code. This is the reason why weak pointers (weak_ptr) exist.
These concept naturally lead to the concept of responsibility for managing the lifetime of an object or (more generally) the management of a used resource. You might want to read about the RAII idiom for instance (Resource Acquisition Is Initialization), and about exception handling in general (writing exception-safe code is one of the main reasons why these techniques exist).
More and more I hear, that I should use smart pointers instead of naked pointers, despite I have effective memory leak system implemented.
What is the correct programming approach on using smart pointers please? Should they really be used, even if I check memory leaks on allocated memory blocks? Is it still up to me? If I do not use them, can this be considered as programming weakness?
If the smart pointers(ex: std::auto_ptr) are strongly recommended, should I use them instead of every naked pointer?
You should use RAII to handle all resource allocations.
Smart pointers are just one common special case of that rule.
And smart pointers are more than just shared_ptr. There are different smart pointers with different ownership semantics. Use the one that suits your needs. (The main ones are scoped_ptr, shared_ptr, weak_ptr and auto_ptr/unique_ptr (prefer the latter where available). Depending on your compiler, they may be available in the standard library, as part of TR1, or not at all, in which case you can get them through the Boost libraries.
And yes, you should absolutely use these. It costs you nothing (if done correctly, you lose zero performance), and it gains you a lot (memory and other resources are automatically freed, and you don't have to remember to handle it manually, and your code using the resource gets shorter and more concise)
Note that not every pointer usage represents some kind of resource ownership, and so not all raw pointer usage is wrong. If you simply need to point to an object owned by someone else, a raw pointer is perfectly suitable. But if you own the object, then you should take proper ownership of it, either by giving the class itself RAII semantics, or by wrapping it in a smart pointer.
You can't just blindly substitute std::auto_ptr for every raw pointer. In particular, auto_ptr transfers ownership on assignment, which is great for some purposes but definitely not for others.
There is a real reason there are several varieties of smart pointers (e.g., shared_ptr, weak_ptr, auto_ptr/unique_ptr, etc.) Each fulfills a different purpose. One major weakness of a "raw" pointer is that it has so many different uses (and has that versatility largely because it does little or nothing to assist in any one purpose). Smart pointers tend to be more specialized, which means they can be more intelligent about doing one thing well, but also means you have to pick the right one for the job or it'll end up dong the wrong things entirely.
Smart pointers allows to define automatically the life-time of objects it refers to. That's the main thing to understand.
So, no, you shouldn't use smart pointers everywhere, only when you want to automate life-time of your objects instead of having, for example, an object managing those objects inside from birth to death. It's like any tool : it solves specific kind of problems, not all problems.
For each object, you should think about the life cycle it will go through, then choose one of the simplest correct and efficient solution. Sometimes it will be shared_ptr because you want the object to be used by several components and to be automatically destroyed once not used anymore. Sometimes you need the object only in the current scope/parent-object, so scoped_ptr might be more appropriate. Sometimes you need only one owner of the instance, so unique_ptr is appropriate. Maybe you'll find cases where you know an algorithm that might define/automate the lifetime of an object, so you'll write your own smart pointer for it.
For example of opposite case, using pools forbids you to use smart_ptr. Naked pointers might be a more welcome simple and efficient solution in this particular (but common in embedded software) case.
See this answer (from me) for more explainations : https://softwareengineering.stackexchange.com/questions/57581/in-c-is-it-a-reflection-of-poor-software-design-if-objects-are-deleted-manuall/57611#57611
Should they really be used, even if I check memory leaks on allocated memory blocks?
YES
The whole purpose of smart pointers is, it help you implement RAII(SBRM), which basically lets the resource itself take the responsibility of its deallocation and the resource doesn't have to rely on you explicitly remembering to deallocate it.
If I do not use them, can this be considered as programming weakness?
NO,
It is not a weakness but a inconvenience or unnecessary hassle to explicitly manage the resources by yourself if you are not using Smart pointers(RAII). The purpose of smart pointers to implement RAII is to provide efficient and hassle free way of handling resources and you would just not be making use of it if you are not using it. It is highly recommended to use it purely for the numerous advantages it provides.
If the smart pointers(ex: std::auto_ptr)are strongly recommended, should I use them instead of every naked pointer?
YES
You should use smart pointers wherever possible because simply there is no drawback of using them and just numerous advantages to use them.
Don't use auto_ptr though because it is already deprecated!! There are various other smart pointers available that you can use depending on the requirement. You can refer the link above to know more about them.
It's a tricky question, and the fact that there is currently a mode to
use smart pointers everywhere doesn't make things any easier. Smart
pointers can help in certain situations, but you certainly can't just
use them everywhere, without thinking. There are many different types
of smart pointers, and you have to think about which one is appropriate
in every case; and even then, most of your pointers (at least in typical
applications in the domains I've worked in) should be raw pointers.
Regardless of the approach, several points are worth mentionning:
Don't use dynamic allocation unless you have to. In many
applications, the only things that need to be allocated dynamically
are objects with specific lifetimes, determined by the application
logic. Don't use dynamic allocation for objects with value semantics.
With regards to entity object, those which model something in the
application domain: these should be created and destructed according
to the program logic. Irregardless of whether there are pointers to
them or not. If their destruction causes a problem, then you have an
error in your program logic somewhere (not handling an event correctly,
etc.), and using smart pointers won't change anything.
A typical example of an entity object might be client connection in a
server, is created when the client connects, and destructed when the
client disconnects. In many such cases, the most appropriate management
will be a delete this, since it is the connection which will receive
the disconnection event. (Objects which hold pointers to such an object
will have to register with it, in order to be informed of its
destruction. But such pointers are purely for navigation, and shouldn't
be smart pointers.)
What you'll usually find when people try to use smart pointers
everywhere is that memory leaks; typical reference counters don't
handle cycles, and of course, typical applications are full of cycles: a
Connection will point to the Client which is connected to it, and
the Client will contain a list of Connection where it is connected.
And if the smart pointer is boost::shared_ptr, there's also a definite
risk of dangling pointers: it's far to easy to create two
boost::shared_ptr to the same address (which results in two counters
for the references).
If the smart pointers(ex: std::auto_ptr) are strongly recommended, should I use them instead of every naked pointer?
In my opinion, yes, you should it for every pointer that you own.
Here are my ideas on resource management in C++ (feel free to disagree):
Good resource management requires thinking in terms of ownership.
Resources should be managed managed by objects (RAII).
Usually single ownership is preferred over shared ownership.
Ideally the creator is also the owner of the object. (However, there are situations where ownership transfer is in order.)
This leads to the following practices:
Make boost::scoped_ptr the default choice for local and member variables. Do keep in mind that using scoped_ptr for member variables will make your class non-copyable. If you don't want this see next point.
Use boost::shared_ptr for containers or to enable shared ownership:
// Container of MyClass* pointers:
typedef boost::shared_ptr<MyClass> MyClassPtr;
std::vector<MyClassPtr> vec;
The std::auto_ptr (C++03) can be used for ownership transfer. For example as the return value of factory or clone methods:
// Factory method returns auto_ptr
std::auto_ptr<Button> button = Button::Create(...);
// Clone method returns auto_ptr
std::auto_ptr<MyClass> copy = obj->clone();
// Use release() to transfer the ownership to a scoped_ptr or shared_ptr
boost::scoped_ptr<MyClass> copy(obj->clone().release());
If you need to store a pointer that you don't own then you can use a raw pointer:
this->parent = inParentObject;
In certain situations a boost::weak_pointer is required. See the documentation for more information.
In general you should prefer smart pointers, but there are a couple of exceptions.
If you need to recast a pointer, for example to provide a const version, that becomes nearly impossible with smart pointers.
Smart pointers are used to control object lifetime. Often when you are passing a pointer to a function, the function will not affect the lifetime; the function does not try to delete the object, and it does not store a copy of the pointer. The calling code cannot delete the object until the function returns. In that case a dumb pointer is perfectly acceptable.
Yes. Assuming you have C++0x available to you, use unique_ptr or shared_ptr (as appropriate) to wrap all the raw pointers you new up. With the help of make_shared, shared_ptr is highly performant. If you don't need reference counting then unique_ptr will get you better perf. Both of them behave properly in collections and other circumstances where auto_ptr was a dumb pointer.
Using smart pointers (shared_ptr or otherwise) EVERYWHERE is a bad idea. It's good to use shared_ptr to manage the lifetime of objects/resources but it's not a good idea to pass them as parameters to functions etc. That increases the likelihood of circular references and other extremely hard to track bugs (Personal experience: Try figuring out who should not be holding onto a resource in 2 millions lines of code if every function invocation changes the reference count - you will end up thinking the guys who do this kind of thing are m***ns). Better to pass a raw pointer or a reference.
The situation is even worse when combined with lazy instantiation.
I would suggest that developers should know the lifecycle of the objects they write and use shared_ptr to control that (RAII) but not extend shared_ptr use beyond that.
In a C++ project that uses smart pointers, such as boost::shared_ptr, what is a good design philosophy regarding use of "this"?
Consider that:
It's dangerous to store the raw pointer contained in any smart pointer for later use. You've given up control of object deletion and trust the smart pointer to do it at the right time.
Non-static class members intrinsically use a this pointer. It's a raw pointer and that can't be changed.
If I ever store this in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to make a shared pointer to my class.
Given that, when is it ever appropriate for me to explicitly use a this pointer? Are there design paradigms that can prevent bugs related to this?
Wrong question
In a C++ project that uses smart pointers
The issue has nothing to do with smart pointers actually. It is only about ownership.
Smart pointers are just tools
They change nothing WRT the concept of ownership, esp. the need to have well-defined ownership in your program, the fact that ownership can be voluntarily transferred, but cannot be taken by a client.
You must understand that smart pointers (also locks and other RAII objects) represent a value and a relationship WRT this value at the same time. A shared_ptr is a reference to an object and establishes a relationship: the object must not be destroyed before this shared_ptr, and when this shared_ptr is destroyed, if it is the last one aliasing this object, the object must be destroyed immediately. (unique_ptr can be viewed as a special case of shared_ptr where there is zero aliasing by definition, so the unique_ptr is always the last one aliasing an object.)
Why you should use smart pointers
It is recommended to use smart pointers because they express a lot with only variables and functions declarations.
Smart pointers can only express a well-defined design, they don't take away the need to define ownership. In contrast, garbage collection takes away the need to define who is responsible for memory deallocation. (But do not take away the need to define who is responsible for other resources clean-up.)
Even in non-purely functional garbage collected languages, you need to make ownership clear: you don't want to overwrite the value of an object if other components still need the old value. This is notably true in Java, where the concept of ownership of mutable data structure is extremely important in threaded programs.
What about raw pointers?
The use of a raw pointer does not mean there is no ownership. It's just not described by a variable declaration. It can be described in comments, in your design documents, etc.
That's why many C++ programmers consider that using raw pointers instead of the adequate smart pointer is inferior: because it's less expressive (I have avoided the terms "good" and "bad" on purpose). I believe the Linux kernel would be more readable with a few C++ objects to express relationships.
You can implement a specific design with or without smart pointers. The implementation that uses smart pointer appropriately will be considered superior by many C++ programmers.
Your real question
In a C++ project, what is a good design philosophy regarding use of "this"?
That's awfully vague.
It's dangerous to store the raw pointer for later use.
Why do you need to a pointer for later use?
You've given up control of object deletion and trust the responsible component to do it at the right time.
Indeed, some component is responsible for the lifetime of the variable. You cannot take the responsibility: it has to be transferred.
If I ever store this in another variable or pass it to another function which could potentially store it for later or bind it in a callback, I'm creating bugs that are introduced when anyone decides to use my class.
Obviously, since the caller is not informed that the function will hide a pointer and use it later without the control of the caller, you are creating bugs.
The solution is obviously to either:
transfer responsibility to handle the lifetime of the object to the function
ensure that the pointer is only saved and used under the control of the caller
Only in the first case, you might end up with a smart pointer in the class implementation.
The source of your problem
I think that your problem is that you are trying hard to complicate matters using smart pointers. Smart pointers are tools to make things easier, not harder. If smart pointers complicate your specification, then rethink your spec in term of simpler things.
Don't try to introduce smart pointers as a solution before you have a problem.
Only introduce smart pointers to solve a specific well-defined problem. Because you don't describe a specific well-defined problem, it is not possible to discuss a specific solution (involving smart pointers or not).
While i don't have a general answer or some idiom, there is boost::enable_shared_from_this . It allows you to get a shared_ptr managing an object that is already managed by shared_ptr. Since in a member function you have no reference to those managing shared_ptr's, enable_shared_ptr does allow you to get a shared_ptr instance and pass that when you need to pass the this pointer.
But this won't solve the issue of passing this from within the constructor, since at that time, no shared_ptr is managing your object yet.
One example of correct use is return *this; in functions like operator++() and operator<<().
When you are using a smart pointer class, you are right that is dangerous to directly expose "this". There are some pointer classes related to boost::shared_ptr<T> that may be of use:
boost::enable_shared_from_this<T>
Provides the ability to have an object return a shared pointer to itself that uses the same reference counting data as an existing shared pointer to the object
boost::weak_ptr<T>
Works hand-in-hand with shared pointers, but do not hold a reference to the object. If all the shared pointers go away and the object is released, a weak pointer will be able to tell that the object no longer exists and will return you NULL instead of a pointer to invalid memory. You can use weak pointers to get shared pointers to a valid reference-counted object.
Neither of these is foolproof, of course, but they'll at least make your code more stable and secure while providing appropriate access and reference counting for your objects.
If you need to use this, just use it explicitly. Smart pointers wrap only pointers of the objects they own - either exclusivelly (unique_ptr) or in a shared manner (shared_ptr).
I personally like to use the this pointer when accessing member variables of the class. For example:
void foo::bar ()
{
this->some_var += 7;
}
It's just a harmless question of style. Some people like it, somepeople don't.
But using the this pointer for any other thing is likely to cause problems. If you really need to do fancy things with it, you should really reconsider your design. I once saw some code that, in the constructor of a class, it assigned the this pointer to another pointer stored somewhere else! That's just crazy, and I can't ever think of a reason to do that. The whole code was a huge mess, by the way.
Can you tell us what exactly do you want to do with the pointer?
Another option is using intrusive smart pointers, and taking care of reference counting within the object itself, not the pointers. This requires a bit more work, but is actually more efficient and easy to control.
Another reason to pass around this is if you want to keep a central registry of all of the objects. In the constructor, an object calls a static method of the registry with this. Its useful for various publish/subscribe mechanisms, or when you don't want the registry to need knowledge of what objects/classes are in the system.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
C++ is all about memory ownership - aka ownership semantics.
It is the responsibility of the owner of a chunk of dynamically allocated memory to release that memory. So the question really becomes who owns the memory.
In C++ ownership is documented by the type a raw pointer is wrapped inside thus in a good (IMO) C++ program it is very rare (rare, not never) to see raw pointers passed around (as raw pointers have no inferred ownership thus we can not tell who owns the memory and thus without careful reading of the documentation you can't tell who is responsible for ownership).
Conversely, it is rare to see raw pointers stored in a class each raw pointer is stored within its own smart pointer wrapper. (N.B.: If you don't own an object you should not be storing it because you can not know when it will go out of scope and be destroyed.)
So the question:
What type of ownership semantic have people come across?
What standard classes are used to implement those semantics?
In what situations do you find them useful?
Lets keep 1 type of semantic ownership per answer so they can be voted up and down individually.
Summary:
Conceptually, smart pointers are simple and a naive implementation is easy. I have seen many attempted implementations, but invariably they are broken in some way that is not obvious to casual use and examples. Thus I recommend always using well tested smart pointers from a library rather than rolling your own. std::auto_ptr or one of the Boost smart pointers seem to cover all my needs.
std::auto_ptr<T>:
Single person owns the object. Transfer of ownership is allowed.
Usage: This allows you to define interfaces that show the explicit transfer of ownership.
boost::scoped_ptr<T>
Single person owns the object. Transfer of ownership is NOT allowed.
Usage: Used to show explicit ownership. Object will be destroyed by destructor or when explicitly reset.
boost::shared_ptr<T> (std::tr1::shared_ptr<T>)
Multiple ownership. This is a simple reference counted pointer. When the reference count reaches zero, the object is destroyed.
Usage: When an object can have multiple owers with a lifetime that can not be determined at compile time.
boost::weak_ptr<T>:
Used with shared_ptr<T> in situations where a cycle of pointers may happen.
Usage: Used to stop cycles from retaining objects when only the cycle is maintaining a shared refcount.
Simple C++ Model
In most modules I saw, by default, it was assumed that receiving pointers was not receiving ownership. In fact, functions/methods abandoning ownership of a pointer were both very rare and explicitly expressed that fact in their documentation.
This model assumes that the user is owner only of what he/she explicitly allocates. Everything else is automatically disposed of (at scope exit, or through RAII). This is a C-like model, extended by the fact most pointers are owned by objects that will deallocate them automatically or when needed (at said objects destruction, mostly), and that the life duration of objects are predictable (RAII is your friend, again).
In this model, raw pointers are freely circulating and mostly not dangerous (but if the developer is smart enough, he/she will use references instead whenever possible).
raw pointers
std::auto_ptr
boost::scoped_ptr
Smart Pointed C++ Model
In a code full of smart pointers, the user can hope to ignore the lifetime of objects. The owner is never the user code: It is the smart pointer itself (RAII, again). The problem is that circular references mixed with reference counted smart pointers can be deadly, so you have to deal both with both shared pointers and weak pointers. So you have still ownership to consider (the weak pointer could well point to nothing, even if its advantage over raw pointer is that it can tell you so).
boost::shared_ptr
boost::weak_ptr
Conclusion
No matter the models I describe, unless exception, receiving a pointer is not receiving its ownership and it is still very important to know who owns who. Even for C++ code heavily using references and/or smart pointers.
For me, these 3 kinds cover most of my needs:
shared_ptr - reference-counted, deallocation when the counter reaches zero
weak_ptr - same as above, but it's a 'slave' for a shared_ptr, can't deallocate
auto_ptr - when the creation and deallocation happen inside the same function, or when the object has to be considered one-owner-only ever. When you assign one pointer to another, the second 'steals' the object from the first.
I have my own implementation for these, but they are also available in Boost.
I still pass objects by reference (const whenever possible), in this case the called method must assume the object is alive only during the time of call.
There's another kind of pointer that I use that I call hub_ptr. It's when you have an object that must be accessible from objects nested in it (usually as a virtual base class). This could be solved by passing a weak_ptr to them, but it doesn't have a shared_ptr to itself. As it knows these objects wouldn't live longer than him, it passes a hub_ptr to them (it's just a template wrapper to a regular pointer).
Don't have shared ownership. If you do, make sure it's only with code you don't control.
That solves 100% of the problems, since it forces you to understand how everything interacts.
Shared Ownership
boost::shared_ptr
When a resource is shared between multiple objects.
The boost shared_ptr uses reference counting to make sure the resource is de-allocated when everybody is finsihed.
std::tr1::shared_ptr<Blah> is quite often your best bet.
From boost, there's also the pointer container library. These are a bit more efficient and easier to use than a standard container of smart pointers, if you'll only be using the objects in the context of their container.
On Windows, there are the COM pointers (IUnknown, IDispatch, and friends), and various smart pointers for handling them (e.g. the ATL's CComPtr and the smart pointers auto-generated by the "import" statement in Visual Studio based on the _com_ptr class).
One Owner
boost::scoped_ptr
When you need to allocate memory dynamically but want to be sure it gets deallocated on every exit point of the block.
I find this usefull as it can easily be reseated, and released without ever having to worry about a leak
I don't think I ever was in a position to have shared ownership in my design. In fact, from the top of my head the only valid case I can think of is Flyweight pattern.
yasper::ptr is a lightweight, boost::shared_ptr like alternative. It works well in my (for now) small project.
In the web page at http://yasper.sourceforge.net/ it's described as follows:
Why write another C++ smart pointer?
There already exist several high
quality smart pointer implementations
for C++, most prominently the Boost
pointer pantheon and Loki's SmartPtr.
For a good comparison of smart pointer
implementations and when their use is
appropriate please read Herb Sutter's
The New C++: Smart(er) Pointers. In
contrast with the expansive features
of other libraries, Yasper is a
narrowly focused reference counting
pointer. It corresponds closely with
Boost's shared_ptr and Loki's
RefCounted/AllowConversion policies.
Yasper allows C++ programmers to
forget about memory management without
introducing the Boost's large
dependencies or having to learn about
Loki's complicated policy templates.
Philosophy
* small (contained in single header)
* simple (nothing fancy in the code, easy to understand)
* maximum compatibility (drop in replacement for dumb pointers)
The last point can be dangerous, since
yasper permits risky (yet useful)
actions (such as assignment to raw
pointers and manual release)
disallowed by other implementations.
Be careful, only use those features if
you know what you're doing!
There is another frequently used form of single-transferable-owner, and it is preferable to auto_ptr because it avoids the problems caused by auto_ptr's insane corruption of assignment semantics.
I speak of none other than swap. Any type with a suitable swap function can be conceived of as a smart reference to some content, which it owns until such time as ownership is transferred to another instance of the same type, by swapping them. Each instance retains its identity but gets bound to new content. It's like a safely rebindable reference.
(It's a smart reference rather than a smart pointer because you don't have to explicitly dereference it to get at the content.)
This means that auto_ptr becomes less necessary - it's only needed to fill the gaps where types don't have a good swap function. But all std containers do.
One Owner: Aka delete on Copy
std::auto_ptr
When the creator of the object wants to explicitly hand ownership to somebody else.
This is also a way documenting in the code I am giving this to you and I am no longer tracking it so make sure you delete it when you are finished.