QPointer containing derived object wont match one with the baseclass - c++

Sorry about the wierd title, feel free to come up with a better one if you can think of one.
Here is my issue.
I have a structure that looks something like this:
QObject -> MyBase -> MyDerived
I then have a function that will take any of the derived types as a QPointer;
void function(QPointer<MyBase> base) {
...
}
The issue is now that I cannot pass QPointer<MyDerived> into this function, which I would if I used standard pointers. Do I have to cast this object to make it fit to the function? Or should I just use normal pointers?
Also, does anyone know the standard behavior when you allocate an object which fails? Should you always do this in a try-block or wrap it in something to check if it's null or not? I read the Qt documentation and they said that most of their classes returned a null value if it failed to allocate. When is that statement true and what can I do if I don't want to use try-catch?

you should use normal pointer. This is what Qt Document says about using QPoiner
"A guarded pointer will automatically cast to a T *, so you can freely mix guarded and unguarded pointers. This means that if you have a QPointer<QWidget>, you can pass it to a function that requires a QWidget *. For this reason, it is of little value to declare functions to take a QPointer as a parameter; *just use normal pointers*. Use a QPointer when you are storing a pointer over time."

As #Kunal mentioned, it's better to pass raw pointer in your case, but I see that you are experiencing pointer ownership problems. Passing raw pointers to object's methods is dangerous, because when your code base grows, you'll soon become confused about which object is the owner of that particular pointer and this can lead to memory leaks very easily. For that reason, I would recommend to use QSharedPointer instead of QPointer or even raw pointer. QSharedPointer supports polymorphism, so you will be able to pass it (as a value) to any function/object you would like, without worrying about ownership, because QSharedPointer will take ownership of the pointer and will delete it when all last instance of QSharedPointer goes out of scope.

Related

C++ pointers and memory leak

I'd like to illustrate one thing I've seen:
class Something {};
void do_something(const Something *p_sth) {}
Then:
do_something(new Something());
should cause a memory leak because when you call new you should also always call delete, right? Would this be a good solution?
void do_something(const Something *p_sth)
{
delete p_sth;
}
Or is it better to use references &? I also find out that smart pointers can solve this, so delete isn't required (it seems as a good thing but I have never used it before). I just want to know what's the best solution for this to avoid the memory leak. Thanks
*Thank you all for your answers. It helped me to clear up few things. I'm also sorry for the code I posted as it was maybe too general.
Your suggestion of assuming the ownership of the pointer and deleting the object has problems.
That behaviour is not idiomatic in c++. Programmers expect that they must delete every object that they allocate with new. If a user of your function expects that they're responsible for deleting the object whose address they pass to the function, then your solution breaks apart. Also, it prevents using your function with objects that must keep existing after the call has ended:
Something* s = new s();
do_something(s);
s.foo() // oops, object was deleted, I can't use it anymore
delete s; // oops, double delete because I'm for some reason not responsible for deleting the object that I allocated
Your solution also prevents using automatically and statically allocated objects with the function.
Something s;
do_something(&s); //oops, do_something assumes that object is dynamically allocated
All of these caveats would have to be documented to the user of the function.
A raw pointer without deleting inside the function has none of these problems. Managing the callers memory should really not be the responsibility of your function. Doing that would break the single responsibility principle. There's nothing wrong with raw pointer parameters when you don't want to transfer or share ownership. If you do want to imply changes in ownership, then use smart pointers which were designed exactly for that.
Smart pointers don't have some of the above problems, but they still prevent using the function with automatic and static objects.
A reference parameter is in many cases ideal. It communicates the caller that they're still responsible for the object. As a bonus, The lack of need for addressof operator allows slightly nicer syntax. Sure, the caller may still forget to manage their memory, but as I pointed out, that shouldn't be your responsibility.
References have one potential drawback. They can't be null. If you don't need null, then it's actually an advantage.
Which solution is ideal, depends on what you need. Following is not true for all corner cases, but should hold for most common cases:
If you want to modify the object, then pass a reference.
Unless you need null, in which case use a pointer
If you just want to read the object, then
If the object is copyable, small (size less than or equal to word), doesn't cointain pointers to dynamic objects and not polymorphic, then pass by value
Otherwise or if you don't know those things because you're writing a template, pass a const reference
Unless you need null, in which case use a pointer
If you want to If you want to transfer ownership, then use unique_ptr
If you want that ownership to be shared, then use shared_ptr
Best is to use a smart pointer
class Something {};
void do_something(std::shared_ptr<Something> p_sth)
{
...
}
That way the ownership is clear when you look at the prototype as well as you get an automatic delete when you leave scope.
I just want to know what's the best solution for this to avoid the memory leak. Thanks
The best solution to ensure there are no memory leaks would be to use std::shared_ptrwhich is a smart pointer which, as soon as it does not have any references, deletes itself. This pointer is best if you have more than on reference to the same pointer. Use std::unique_ptr if there is only one reference at a given time.
This will prevent memory leaks and I also prefer using smart pointers rather than standard pointers as they are very powerful. Also, retaining to the question:
Or is it better to use references &?
Use references wherever you need to reference the object, if you delete the reference, being a smart pointer, it will delete the pointer as well (Being there are no other references to that pointer)
I hope this answers your questions :)
Prefer to avoid the use of raw pointers.
If you do not need a heap allocation and can use a stack allocated variable, then prefer to pass by reference (or even pass by value if an appropriate move constructor is in place, but that's a topic for another day).
If you need a heap allocation (for polymorphism, dependency injection, information hiding, transfer of ownership etc.) then determine what the ownership semantics will be for that object and use the appropriate smart pointer to manage those semantics.
If all else fails and you must use a raw pointer (perhaps you are dealing with a legacy interface or a C interface, or something similar) then again, clearly define your ownership semantics and document them to make it clear who is responsible for deleting the heap allocated object, etc.
If you must have a raw pointer to a stack allocated object then document that you will not be deleting the pointer and be careful about documenting the lifetime of the pointer to avoid accessing the object after it has gone out of scope.
Cleanest solution would be to avoid the pointer completely.
And yes, a reference is a good idea.
void do_something(const Something &p_sth) {}
Then you can declare your 'something' on the Stack.
void function_that_does_something()
{
Something mySomething;
do_something( mySomething );
}
It is always best to let the compiler do the cleanup for you.

How to enforce non-ownership of a pointer?

I have a method which creates an object in an auto_ptr, sticks that auto_ptr into a vector, and then returns a raw pointer to the object for convenience.
The problem with this design is that it returns a raw pointer. It's really easy for the caller to misunderstand that this pointer is non-owned and wrap the result of this call into a managed pointer, which causes a memory access violation when that memory gets double free'd.
int main (void)
{
{
std::auto_ptr<int> foo = ThisMethodReturnsNonOwningPtr(); // Uhoh
}
ThisMethodUsesThePtr(); // Crash
return 0;
}
Ideally, I would like to return something like a pointer which can not be converted to a managed pointer so I don't have to worry about the caller doing this.
Alternatively, I might just return an index into the array, but it's real convenient just being able to pass the pointer around, and who knows maybe I will end up shuffling or sorting the array later.
First, if you can stick an auto_ptr into a vector, it's time to
upgrade your compiler or your library. This hasn't been legal
since the first standard in 1998. If you've got C++11, you can
use std::unique_ptr; if not, you'll need to keep raw pointers
in the vector. In both cases, you'll want to wrap the vector:
with std::unique_ptr, so that the client doesn't have to do
anything fancy to get the actual pointer, and with raw pointers,
so that you can manage the memory associated with them.
For the rest, just return a raw pointer. If you have
programmers that go around deleting random pointers, you're sunk
anyway; most of the time, raw pointers are for navigation, and
are just as likely to point to an object with static lifetime as
to anything else.
Stop using auto_ptr and start using unique_ptr or shared_ptr. The latter has reference counting so you can safely return the object and others can use it. The data it points to will not be freed until all references are released.
there is no other alternative if you need to safely return a pointer to the object and still be able to alter the vector. You could use a unique_ptr to prevent a caller from treating the returned pointer as if it owned it.
Last resort is to slap comments on the code to say that the vector owns the object and the pointer is only to be used as a convenience. Its not as good as getting the compiler to check calling code, but it can be the only way if you restrict your options as you mentioned.
Create a wrapper class template raw_ptr<T> which encapsulates a T*.
If you now implement operator* and operator-> but no conversion operator, you can no longer assign this pointer to another smart pointer, because that assignment would require two custom conversions (raw_ptr<T> → T* → smart_ptr<T>), which is not allowed in C++.
Notice that, as others have said, you should not use auto_ptr<T> – it’s deprecated for good reasons. Use std::unique_ptr<T> instead. For one thing, you cannot actually safely stick auto_ptrs into a std::vector, great care has to be taken to not accidentally copy (and thus invalidate) such pointers.
I'm always reluctant to write answers that depend on boost since not everyone is able to use it and it's almost always overkill to pull it in for just one little thing, but if you have it anyway, you could return a boost::optional<&>. On the surface it doesn't seem an optional reference could work, but it (mostly) does. See boost's documentation.
This would give you the nullability you require (return boost::none to indicate an error) while making it very clear that the caller is not to take ownership of the object.
If you don't want the object to be deleted in conventional means using delete operator, you could make the destructor of the class private and implement destroy() function which self-destructs the object.
Better would be if you could make the function return something like shared_ptr.
A third option could be just to have a class something like template<typename> struct non_ownership_ptr; which the function returns instead of a raw pointer. This pointer class just holds the pointer and you would have to explicitly use auto_ptr<T> p=foo().non_owned_ptr; to avoid (or at least reduce) accidental assignment to auto_ptr or such.

Dealing with pointers that may not point to anything

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.

How do I prevent deletion of a pointer without using const?

I have a class that contains a vector of object pointers. I have a GetObject(..) function in that class that looks through the vector, finds the object desired, and returns a pointer to it. However, if the user of the class does a delete() on that returned pointer, my program will crash because the vector still has a pointer to that, now invalid, object. So, in my GetObject() class, I can return a const pointer, but that doesn't solve the problem because you can still delete the object. The object is mutable so I can't return a pointer to a const object. I suppose I could prevent deletion by returning a reference to the object but I have my function returning NULL if there is an error. I guess I can pass back the object reference via the parameters and then return and error number like this
//-1 on object on found. 0 for success. Object is passed back in
// the function parameter result.
int MyObject::GetObject(int object_id, Item& result)
Is this the best solution for such a situation?
The best way to solve this problem is to use a shared-ownership smart pointer like shared_ptr, which you can find in Boost, C++ TR1, and C++0x.
A smart pointer is a container that manages the lifetime of your dynamically allocated object for you. It takes responsibility for deleteing the object when you are done using it.
With a shared ownership smart pointer, you can have multiple smart pointers that all share ownership of the dynamically allocated object. A reference count is kept that keeps track of how many smart pointers have ownership of the object, and when the last owning smart pointer is destroyed, the dynamically allocated object is deleted.
It is extremely difficult to manage resources manually in C++, and it's very easy to write code that looks correct and works right most of the time but that is still not correct. By using smart pointers and other resource-owning containers (like the standard library containers), you no longer have to manage resource manually. It is significantly easier to write correct code when all of your resource management is automatic.
Automatic resource management in C++ is accomplished using a design pattern called Resource Acquisition is Initialization (RAII), which is arguably the most important design pattern you as a C++ programmer should become familiar with.
Anybody in your code could also try to de-reference NULL. You going to stop them doing that too? If your container owns the object, and you make this clear (returning a raw pointer is usually pretty clear or mention in docs), then anyone who deletes it, the result is their own fault. The only way that you could guarantee the prevention of the deletion of the object is to prevent the user from ever gaining a native reference or pointer - in which case they just can't access the object.
Who are clients of your class? If they are not your mortal enemies you could just ask them nicely not to delete the object. Otherwise, there will always be a way for "them" to mess you up.
Okay, one possible solution is to make destructor private. That will prevent everyone from deleting the object. But then the object has to delete itself (delete this) somehow, maybe through some function called DeletObjectButDontBlameMeIfAppCrashes. If the owner is some other class then you can set the destructor to protected and owner class as friend of this class.
You should return a reference to the object. There are two ways to handle the case when there is no object found.
First, you can use the Null Object Pattern in order to implement a special value for that case. That might not make sense for your case though.
The other way is to split it up into two methods, one which can be used to check if an appropriate element exists, and one to retrieve it.
Many STL-containers or algorithms implement both of these, either by returned a past-the-end iterator, or by having empty() returns false as a prerequisite of calling a method like front or back.
If you can use the boost libraries, smart pointers can be used to ensure that pointers stay valid. Essentially, each reference to a smart pointer increases its "use count" by 1. When the reset function is called on a reference, the reference goes away and the use counter decrements. As long as some object is still holding on to a smart pointer, the reference will be valid. Note that the other classes will be able to change what its pointing to, but can't delete it.
(My description deals mainly with smart pointers specifically - the different types of pointers vary a little, but the general idea remains the same).

How to prevent deletion of pointers managed by a QSharedPointer

I have some intermittent segmentation faults in a Qt application. I think the problem is related to our (bad) use of QSharedPointer. The Qt Documentation states :
QSharedPointer::QSharedPointer ( T * ptr ) :
Creates a QSharedPointer that points to ptr. The pointer ptr becomes managed by this QSharedPointer and must not be passed to another QSharedPointer object or deleted outside this object.
I think we are doing both must not... :/
Is there a OOP way to enforce that the pointer managed by QSharedPointer cannot be deleted or passed to another QSharedPointer?
The best solution will be to have a compiler error.
The normal pattern is to put the new statement inside the smart pointer's constructor, like this:
QSharedPointer<Obj> p (new Obj(2));
That way you never have a reference to the naked pointer itself.
If you refactor your code so that all new operator are in lines like these, all your problems will be solved.
Well, an OOP-esque way would be to create the raw pointer as a private member in a wrapper class, and only perform actions on the pointer through methods that act on the shared pointer. kind of silly though, isn't it?
Or you could make your class with the raw pointer a base class to your other classes and make the raw pointer a private member in the class. In this regard, you're more or less creating an abstract class that does nothing. Your derivative classes must instead do all the work, and since they can't access the raw pointer, compilation will fail... this doesn't stop someone from just copying the raw pointer value out of the shared pointer, though.
In the end, I think your best policy is to manuall change all of the functions in question to use either a shared pointer or else a raw pointer. You can copy one shared pointer to another safely, so why no just go that way?
Edit:
I might add that regardless of whether or not you're using shared pointers, it sounds like you're having ownership issues. If a pointer was created in one scope, it should be deleted in that scope, unless the function that it is passed to contractually takes ownership of the pointer. Using a shared pointer in this scenario will only caused different bugs, eventually. It sounds like you have design issues deeper than just the sharing of pointers.
I'm not familiar with the particular Qt implementation of a shared pointer, but as a general guideline : attempting to mix raw pointers with managed pointers usually ends in blood. Once you 'trust' a shared pointer implementation in taking ownership of your dynamically allocated data, you should under no circumstances try to manage the object lifetime yourself (for example by deleting the provided pointer).
Is there a OOP way to enforce that the pointer managed by QSharedPointer cannot be deleted ?
I guess you could imagine some weird technique where the pointed type would have a private destructor and declare QSharedPointer as friend (which would effectively prevent any 'outside deletion' from compiling), but I wouldn't bet that anything good can come out of this (and note that it will make your type absolutely unusable unless new'ed and transfered to a QSharedPointer).
Is there a OOP way to enforce that the pointer managed by QSharedPointer cannot be passed to another QSharedPointer?
I can't think of any, and that is another reason why you should avoid manipulating the raw pointer once it's ownership has been transferred to a QSharedPointer.
Check your code for all .data() usage and make sure what they return is neither stored nor deleted. I don't think a hard compiler error would be good, because sometimes it's okay to pass the raw pointer, e.g. to a function that doesn't store nor delete passed pointers. (Especially when using 3rd-party code, you cannot always change everything to use shared pointers, and often you want it to work with both, raw and shared ptrs).
One could mark QSharedPointer::data() as deprecated (by patching Qt), to get a compile time warning.