It's rather not a question "how to do it" it's rather "how to do it the right way"
I'm developing an editor in Qt where different widgets display the children and its (member) variables. Each of these widgets should hold a reference/pointer to the edited child to display and change their member variables.
The first attempt was the old ANSI C way I learned (and still kinda stuck in) with simple raw pointer to the used objects. It works fine but since the C++11 standard supports smart pointer and using them is recommended I'm trying to use them.
The problem is, I'm not quite sure what's the "best way" to use them in this case...
After reading Smart Pointers: Or who owns you baby? and Which kind of pointer do I use when? and a few others I came to different conclusions:
The first is to use a*unique_ptr since the edited object is clearly the owner which creates and also deletes its children. The widgets are simply referring to the child to show or change them.
The problem is how should the widgets refer to the child...
for now I'm simply still using a raw pointer I got with the get() method of the unique_ptr but this seems kinda flawed to me.
I still can accidentaly call delete on the pointer and cancel the benefits of the smart pointer.
The second approach is to use a shared_ptr because many objects refer to the child and edit it. Also accidentaly deleting it in one widget would do no harm because it is still owned by other objects.
The problem is they own it. When I want to delete it from the edited object I also have to signal all widgets to delete it before it is really gone. (this again seems flawed and error-prone)
I'm not really content with both ways. Is there a clean(er) way to point to the unique_ptr child of the object? Or am I missing a completely different and better approach to this problem?
Your use case doesn't translate directly to requirements (what if someone else deletes the widget while you're editing it?) but I'll assume you don't need anything beyond a naked pointer.
The Standard Library does not provide any strict pointer-observer class. Among observer entities:
Nullable, mutable pointers of native type (T *)
Non-nullable, non-mutable references of native type (T &)
Non-nullable, mutable references/proxies of class type (std::reference_wrapper<T>)
Nullable, self-validating, mutable pointers to managed objects (std::weak_ptr<T>)
If you want a non-nullable, mutable pointer to a non-managed object, which is a fairly reasonable thing to want, you can roll your own.
But naked pointers aren't that bad. The only difference is that it can be nullptr, and that it doesn't have a nice, long, explicit name inside namespace std.
You want to use a shared_ptr in place of your unique_ptr and weak_ptr's in place of your raw pointers. This will give exactly what you're after. The weak_ptr's will not interfere with the edited object's ability to delete the underlying object.
If you are using Qt, you might consider using the Qt smart pointers instead of std:: smart pointers:
QShardPointer and QWeakPointer
or for QObjects:
QPointer (or QWeakPointer, esp in Qt4)
or to achieve copy-on-write data sharing, Qt container and QString style:
QSharedDataPointer
There are other pointer classes too, but some of the above are most likely to do what you want. Also important, if you have your data in Qt container classes, QStrings or such, they handle their own memory with copy-on-write semantics, and should generally be passed around as plain values (sometimes as references) instead of pointers.
But most importantly, do not use std::unique_ptr or std::shared_ptr with QObjects which have parents, because if the parent deletes the child first, then the std:: pointer will delete it again, crashing the program (other way will work ok, child will notify it's parent that it's deleted). In other words, there's a good chance of subtle bugs if you mix QObjects and std:: pointers, so just don't do it. It's not clear from your question if you are doing it, saying just in case.
There is a proposal for the world's dumbest smart pointer, which is a non-owning pointer. Basically, it is a T* that says "oh, and by the way, I don't claim any ownership over this data".
In this case, you have to manage that the observing/passive/dumb pointer gets reset if the unique_ptr goes away -- half manual lifetime management. Using a raw T* with a name that indicates it is non-owning works just as well prior to having the above.
There are benefits to doing the above, especially when you have objects with dependent lifetime.
If you do not, then a shared_ptr and weak_ptr works. Note, however, that anyone with a weak_ptr can create a new shared_ptr, which could extend the lifetime of the shared object beyond the original shared_ptr. This must happen, as there is otherwise a race condition whereby the user of the weak_ptr ensures its data is valid, then goes to use it, but before they do the shared_ptr's data is destroyed.
So the weak_ptr must either by able to prevent the shared_ptr from being destroyed (blocking in multi-threaded context, causing it to "fail" somehow in single-threaded contexts). "Fail" in this case consists of extending the lifetime, which solves both the multi-threaded and the single-threaded problem.
(The single threaded problem is that you verify the weak_ptr is good, do something that causes the shared_ptr to reset, then continue to want to use the weak_ptr's data without rechecking. Naively, it could be avoided with exceptions, but upon closer inspection you run into problems where you'd have to code all methods to check for deletion before accessing this and throw if this is deleted, a pretty harsh requirement!)
Related
I want to use C++11 Smart Pointers in new projects, and encounter a problem. Many current projects still use raw pointers as parameters in their interface and have no interface for smart pointers, e.g. QMainWindow::setCentralWidget.
To keep type consistent, I have to pass the stored pointer from get() like this segment:
QMainWindow win;
std::shared_ptr<QWidget> scrollArea{ std::make_shared<QScrollArea>() };
// QScrollArea is a derived class of QWidget.
win.setCentralWidget(scrollArea.get());
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
Will it cause memory leak or other problems if some methods in Qt do that?
I've checked the latest C++ Standard CD and found nothing on that. Seems it's an undefined behavior.
If doing this is an undefined behavior and dangerous, is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
There's no such way in the general case. For each "legacy" interface you want to use, you must read its documentation to see how it interacts with ownership (which is what std smart pointers encapsulate). A single object can only be managed by one ownership scheme.
With Qt in particular, it's definitely not safe to mix smart pointers and Qt management. Qt's parent/child relationship between QObjects includes ownership semantics (children are deleted when their parent is), so you cannot safely mix this with any other ownership scheme (such as std smart pointers).
Note that the Qt docs you link to explicitly state that "QMainWindow takes ownership of the widget pointer and deletes it at the appropriate time."
Unfortunately, if you are using an interface that uses raw pointers, you will need to consult the documentation to determine if the method does or does not take ownership of the provided pointer.
If the function takes ownership, then you must invoke .release() to transfer the ownership to the function. If the function does not take ownership, then you would pass the object with .get().
Will it cause memory leak or other problems if some methods in Qt do that?
It won't introduce a memory leak, since the memory is afterall released. However, since both QT and the shared_ptr would call delete on that memory, you would likely get some nice heap corruption (UB in general).
is there a safe way to use smart pointer(s) with the interface for raw pointer(s)?
Sure. Don't have unrelated entities manage the same memory. For that it is adavantegous to use unique_ptr instead of shared_ptr when possible. With unique_ptr you could call .release() to release the memory from the control of the smartpointer, thus giving you the ability to give control over to QT.
Of course you need check the documentation to see when you have to manage memory yourself and when QT will do it for you.
I don't think you should be doing any deleting with the QWidget.
http://qt-project.org/doc/qt-4.8/qmainwindow.html#setCentralWidget
Note: QMainWindow takes ownership of the widget pointer and deletes it
at the appropriate time.
If you have to use smart pointers, you can use a weak_ptr which won't own or destroy it.
If you are using an interface which takes raw pointers, you already have the problem that you must know who is responsible for the lifetime of those pointers.
Adding shared_ptr into the mix doesn't change this.
If the interface will possibly delete the object, then you cannot use std::shared_ptr safetly. std::shared_ptr must control the lifetime of its objects and there's no way around this (without adding another level of indirection)
You can however get some use out of std::unique_ptr. If an interface will not delete a pointer, you can safetly pass in ptr.get(). If an interface takes ownership of the lifetime of that object, pass in ptr.release() and you give up controlling the lifetime yourself.
All in, you can get some usefulness out of smart pointers even with a legacy codebase, but you've got to be a little careful.
But I can't make sure whether other methods in Qt execute operator delete on the stored pointer of scrollArea.
If the widget has a parent, then the QT's memory management will release that object. In that case you must not use a smart pointer, because your application will try to release it twice, and that is an undefined behaviour.
I have a set of objects in a vector of pointers to their baseclass held inside a manager:
std::vector<object*> objectVec;
Classes may wish to spawn one of these objects using the Add() method in the manager. The problem is that they then subsequently need to set or update these objects themselves. I've decided to have Add() return a pointer to the object itself, which is stored in whatever class has decided to spawn one. The problem is dealing with the case where the object behind that pointer may have been deleted.
Add looks like this:
object* ObjectManager::Add(object* obj)
{
objectVec.push_back(obj);
return objectVec.back();
}
and used like this:
objectptr = ObjectManager::OMan()->Add(new object());
Where objectptr is a member of whatever class has called the function. So should that particular object be deleted, the pointer returned by Add would point to rubbish.
Is it my responsibility to ensure that whateverclass::objectptr is always set to NULL if this object is deleted? Or can this be dealt with using some sort of smart pointer? The problem being that I don't need to use a smart pointer to deal with the possibility of a memory leak, but to deal with the case where the stored pointer has become invalid.
Please let me know if i've been unclear, or if the question is badly formed.
Any help would be greatly appreciated.
Yes, you can store smart ptr's instead of raw ptr's in your vector. In this case if somebody releases an object, it's not deleted until the last reference is not released (the one held in vector in your case). You can use boost::shared_ptr or std::shared_ptr (C++11).
If this is not what you want, you can use boost::weak_ptr to store references in your vector. weak_ptr doesn't increment reference counter so if somebody releases an object, it's get deleted, but reference (weak_ptr) stored in your vector allows you to check this.
You likely want weak_ptr and shared_ptr. shared_ptr is a general smart pointer class. weak_ptr is an observer of shared_ptr. When all the references of the shared_ptr go away, instances of weak_ptr "become null" and are easier to deal with than a pointer to a deleted object.
These classes come with Boost.
http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/shared_ptr.htm
http://www.boost.org/doc/libs/1_47_0/libs/smart_ptr/weak_ptr.htm
And if I'm not mistaken, there are equivalents built into std namespace on compilers that implement newer C++0x standards. Visual C++ keeps has this built in.
http://blogs.msdn.com/b/vcblog/archive/2011/02/16/10128357.aspx
Oh shoot, looks like everyone else beat me to the answer...
Best is to forget this "manager" idea, but if you do or if you don't, the solution to shared ownership is the same as always, use boost::shared_ptr.
Or, with relatively new compiler, use std::shared_ptr.
Considering that with shared_ptr the ownership issue is taken care of already, then ask yourself, what is it that the "manager" manages?
Cheers & hth.,
Is it my responsibility to ensure that whateverclass::objectptr is always set to NULL if this object is deleted?
You're writing the class, so it's up to you to decide. This is a design decision and either choice is admissible, provided that you document it:
design the application
write the documentation/specification
write the code to matches the specification
Or can this be dealt with using some sort of smart pointer?
Using a smart pointer (strong or weak version) will help achieve whatever behavior you chose for the class. However, it will also strongly affect the client code. In the following code:
class Scene
{
// can't use this object in a call to `ObjectManager::Add()`,
// assuming it uses a smart pointer to deal with object lifetimes.
Object myLight;
};
The use cases for the ObjectManager class should be taken into consideration, on top of simplicity of implementation. Think "write once, use a lot".
Dangling pointers and memory leaks are two different issues, but a proper shared pointer can protect from both. For this particular case, I'd suggest boost::shared_ptr.
Use std::vector<boost::shared_ptr<BaseType>> for the vector type and also have the objects that hold the bare pointers now hold instead a boost::shared_ptr<BaseType>. This will ensure that the pointers will stay valid in the vector and in the objects as long as one of those objects still exist.
If you have differing requirements, you can use a boost::weak_ptr in one of the places holding the pointer (either the vector or the object).
Also, the object can hold a derived type instead of a base type (boost::shared_ptr<DerivedType>) and you can convert between them using boost::shared_static_cast.
Here is the documentation for all of these concepts.
I have a GUI to interact with the user, but I have an OOP design problem with this.
Through a dialog the user specifies CDiscreteDistributions and they are stored in a std::vector<CDiscreteDistribution*> in the MyAppDoc class for serialization. Through another dialog the user chooses a type of CDistribution for a particular CParameter. CDiscreteDistribution, CConstantDistribution, and CContinuousDistribution inherit CDistribution, and CParameter has a polymorphic pointer to a CDistribution member variable. MyAppDoc has a container class of CParameter. Thus the CDiscreteDistributions are pointed two twice, but only exist once.
In summary, MyAppDoc has
std::vector<CDiscreteDistribution*>
CContainer which has many CParameter which have
CDistribution* which can point to one of
CDiscreteDistribution which is one of the CDiscreteDistribution*s stored above
CConstantDistribution created/destroyed by CParameter
CContinuousDistribution created/destroyed by CParameter
This design pattern is causing me various nightmares in porting the app to use shared_ptr due to double deletes and serialization (boost). Should one of the pointers to CDiscreteDistribution be a weak_ptr? If so where should own the pointer?
Thanks for any help!
EDIT:
I re-thought the reasoning for having std::vector<CDiscreteDistribution*> and it was just to avoid copying the vector into and out of the GUI. But the objects are quite small, and so I've broken the link between them and suffer the minor performance implications. Now MyAppDoc has:
std::vector<CDiscreteDistribution>
CContainer which has many CParameter which have
CDistribution* which can point to one of
CDiscreteDistribution created/destroyed by CParameter, copied from one of the CDiscreteDistributions stored above
CConstantDistribution created/destroyed by CParameter
CContinuousDistribution created/destroyed by CParameter
I think part of the problem was boost::serialization made two shared_ptrs for each CDiscreteDistribution that weren't aware of each other's existence. Now the only issue is backwards compatibility to files created with the previous versions.
I figure this 'solution' is actually just avoiding a proper design!
The question is described not enough to understand the full situation, complications and exact problem, but in general -
I assume you want to use shared_ptr to not have to manually delete() objects
If so, see if you can solve it by not using shared_ptr, but rather using boost::ptr_vector instead of a vector of raw pointers; the ptr_vector will then handle memory management for you.
I'm not even sure what the shared_ptr would bring you - it's quite obvious, I'd say from my limited understanding of the situation, that the Doc owns the CDiscreteDistribution objects. Whoever owns the other two types of Distributions is responsible for deleting them; this can be done though a shared_ptr or otherwise. (you say 'locally instanced' but that doesn't mean much - are they instantiated on the heap or the stack? What is their lifetime? Why is their lifetime different from the DiscreteDistribution objects? What is 'local' - local to what?)
I agree with Roel that the question is not fully specified. But having done several extensive conversions from raw pointers to shared_ptr, I can give you a little advice.
weak_ptr should not be necessary unless you have circular dependencies. In other words, if an object A has a shared_ptr to object B and object B has a shared_ptr back to object A. In this case, it's impossible for the reference count of either pointer to go to 0, so you would either need to manually intervene to break the cycle, or use weak_ptr to designate one side as dependent.
I'm confused why you have issues with double deletion when using shared_ptr. One of the advantages of smart pointers in general is that you don't have to actually delete them. If you've converted all your raw pointers to shared_ptr, you shouldn't have this problem. If your CConstantDistribution and CContinuousDistribution objects are actually locals rather than allocated with new (I can't tell 100% if this is the case from your description), you can make them shared_ptr objects that are initialized in your constructor, if you can change the app's code. This would allow you to make your std::vector<CDiscreteDistribution*> a container of shared_ptr to CDiscreteDistribution instead. At that point, you shouldn't have to worry about deleting those objects at all, unless you have circular references as described above. Even if you do, you'd have converted a double-delete crash to a memory leak, which is generally less bad.
Serialization can be tough. Since you've tagged the question with MFC, I'll assume you're using MFC serialization. I generally don't have problems when wrapping everything in shared_ptr when I serialize out to a file -- I just use .get() on the smart pointer object and serialize the resulting raw pointer. When I serialize in, I read the raw pointer from the serialized file and wrap it in the shared_ptr candy coating at that point. It's a little extra code in the serialization function, but it works.
If I've guessed inaccurately on some of your situation, feel free to add a comment. I'd be happy to help further if I can.
there are already a couple of questions regarding this topic, but I am still not sure what to do: Our codebase uses shared_ptr at many places. I have to admit that we did not define ownership clearly when writing it.
We have some methods like
void doSomething(shared_ptr<MyClass> ptr)
{
//doSomething() is a member function of a class, but usually won't store the ptr
ptr->foo();
...
}
After having discovered the first (indirect) circular dependencies I would like to correct the mistakes in our design. But I'm not exactly sure how. Is there any benefit in changing the method from above to
void doSomething(weak_ptr<MyClass> ptr)
{
shared_ptr<MyClass> ptrShared = ptr.lock();
ptrShared->foo();
...
}
?
I am also confused because some people say (including the Google Style guide) that in the first place it's important to get ownership correct (which would probably mean introduction of many weak_ptrs, e.g. in the example with the methods above, but also for many member variables that we have). Others say (see links below) that you should use weak_ptr to break cyclic dependencies. However, detecting them is not always easy, so I wonder if I really should use shared_ptr until I run into problems (and realize them), and then fix them??
Thanks for your thoughts!
See also
shared_ptr and weak_ptr differences
boost::shared_ptr cycle break with weak_ptr
boost, shared ptr Vs weak ptr? Which to use when?
We did not define ownership clearly.
You need to clearly define who owns what. There's no other way to solve this. Arbitrarily swapping out some uses of shared_ptr with weak_ptr won't make things better.
There is no benefit in changing your design above from shared_ptr to weak_ptr. Getting ownership right is not about using weak_ptrs, it's about managing who stores the shared_ptr for any significant length of time. If I pass a shared_ptr to a method, assuming I don't store that shared_ptr into a field in my object as part of that method, I haven't changed who owns that data.
In my experience the only reason for using weak_ptr is when you absolutely must have a cycle of pointers and you need to break that cycle. But first you should consider if you can modify your design to eliminate the cycle.
I usually discourage mixing shared_ptr's and raw pointers. It inevitably happens (though it probably shouldn't) that a raw pointer needs to be passed to a function that takes a shared_ptr of that type. A weak_ptr can be safely converted to a shared_ptr, with a raw pointer you're out of luck. Even worse, a developer inexperienced with shared_ptr's may create a new shared_ptr from that raw pointer and pass it to the function, causing that pointer to be deleted when the function returns. (I actually had to fix this bug in production code, so yes it does happen :) )
It sounds like you have a design problem. shared_ptr provides
a simple to use implementation for specific design solutions,
but it (nor anything else) can replace the design. Until you
have determined what the actual lifetime of each type of object
should be, you shouldn't be using shared_ptr. Once you've done
that, most of the shared_ptr/weak_ptr issues should disappear.
If, having done that, and determined that the lifetime of some
objects does depend on that of other objects, and there are
cycles in this dependency, you have to determine (at the design
level, again) how to manage those cycles---it's quite possible,
for example, that in those cases, shared_ptr isn't the correct
solution, or that many of the pointers involved are just for
navigation, and should be raw pointers.
At any rate, the answer to your question resides at the design
level. If you have to ask it when coding, then it's time to go
back to design.
Some people are right: you should at first have very clear picture about objects' ownership in your project.
shared_ptrs are shared, i.e. "owned by community". That might or might not be desirable. So I would advise to define ownership model and then to not abuse shared_ptr semantics and use plain pointers whenever ownership should not be "shared" more.
Using weak_ptrs would mask the problem further rather than fix it.
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.