does Direct 2D leaves pointers in the memory? - c++

Obviously, working with Direct X, we are heavily working with pointers, but the question I couldn't find on MSDN is: does Direct X create memory with "new" internally?
Example:
ID2D1GeometrySink * pSink;
path->Open(&pSink); // did this command use "new" internally?
In MSDN, they only used pSink = NULL, to create multiple sinks from the same variable. So will be there any memory leak?

As DirectX uses COM it must follow COM rules of maintaining memory.
So if a method returns an interface pointer, a caller is responsible for releasing this pointer.
In general, we never know nature of the returned pointer. In this particular case we don't know whether ID2D1GeometrySink allocated within this method, or this is a precreated object. All what you need to know about managing returned pointer is that you should call Release when you don't need this pointer.
Also I would suggest to use wrappers that call Release in destructor, I mean classes like CComPtr and others. In this case you don't need to call AddRef / Release yourself.

There are a few questions here.
Yes, the call to path->Open allocates resources for your sink. pSink is a pointer but you pass &pSink to the Open method - a pointer to the pointer. The call obtains a geometry sink and sets your pSink variable to point to that sink. It can do this because you have passed the address of your pointer rather than the value of the pointer.
Will it leak memory?
Yes, if you don't release the sink when you are done with it. The examples are clear on this, calling SafeRelease(&pSink); when finished with the object.

Related

Do I have to call a release function using a ComPtr?

I'm using a smart pointer or a ComPtr. I'm using it with my directX application and I haven't seen other people call the release function in their code using the ComPtr. So does the smart pointer release the data that the smart pointer is referring to or do I need to do it manually? I don't know if this makes since so tell me if it doesn't and I will respond with better detail.
You should never call AddRef or Release on a ComPtr, and by default you can't. You have to use hacky patterns like comPtr.Get()->Release to do it, and you are mostly like going to cause problems.
The purpose of Microsoft::WRL::ComPtr is to make COM pointer cleanup automatic, both in normal code and when handling C++ exceptions. Making a copy of a ComPtr to another ComPtr automatically increase the ref-count, and each time a ComPtr variable goes out of scope it automatically decreases the ref-count. This greatly simplifies error-handling and cleanup which is why the code you are looking at isn't awash in calls to Release.
There are special methods Attach and Detach for 'transferring ownership' so that the ref-count is not changed, but they are for special use cases. There are also some tricks you can do with Swap as well that are very useful for robust coding.
If you want to explicitly 'release' a ComPtr variable, you can assign null to it or better yet use Reset.
Like with all smart-pointers you should think about the lifetime of your pointer to decide how to use it. If a function or class is going to 'own' the object pointed to, then use of a smart-pointer is the right way to do it. If the function is just going to work with the object and then return without any change in lifetime, the function should take a raw pointer instead with you using the Get method on the ComPtr when calling it. Otherwise your program wastes a lot of time needlessly increasing and decreasing the ref-count when the ownership of the object was not actually in question.
Another option is to pass the smart-pointer parameter as const ComPtr& which avoids the ref-count cycling, but it has the side-effect of forcing the caller to use ComPtr when the raw pointer is more agnostic to the caller's object lifetime policy and therefore more flexible.
I've got a write-up of how to use ComPtr on the DirectX Tool Kit wiki. You can also see MSDN.
For non-COM objects, std::unique_ptr is a great option. You can also use std::shared_ptr and std::weak_ptr but there are a lot of performance implications and edge-cases to worry about in the shared case, so sticking to ComPtr for COM and std::unique_ptr for heap-allocated objects with a single-owner is best practice.
You should not normally need to call AddRef or Release through the smart pointer - the entire point of ComPtr is that it calls those for you.
You might still need to call them if you're converting a smart pointer to a "manually managed" (normal) pointer.

Is there a safe way to use C++11 Smart Pointer and the Interface for Raw Pointer together?

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.

Manually release ComPtr

I'm using ComPtr (Microsoft::WRL) to manage some DirectX11 resources.
How can I manually release it?
The "ReleaseAndGetAddressOf" method if I understand correctly, only frees the pointer and not the resource itself (which is returned), and I'm not sure about the "Reset" method.
The only alternatives I could think of are manually calling the pointer destructor, or after obtaining the raw pointer from "ReleaseAndGetAddressOf" calling "Release" on that, which I would like to avoid.
The source code for WRL is provided, have a look at include/winrt/wrl/client.h. The embedded COM pointer (ptr_ member) is released by the InternalRelease() function. Making any of the following a way to release the pointer suitable candidates:
the destructor. The reason to use ComPtr<>
assigning nullptr
using ReleaseAndGetAddressOf(), the long way around
calling Reset()
So assigning nullptr or calling Reset() are a good fit, take your pick. Or don't use it at all if you just want to manage the interface pointer yourself, it certainly isn't required to use ComPtr.
You can assign a null pointer.

Is it bad manners to return a heap allocated pointer from a function?

Before boost::shared_ptr, was it considered a bad practice to return a heap allocated pointer from a function, since the caller will be required to remember to free() that object?
Or, was it considered "normal"?
I don't consider it bad practice, so long as your API also provides an equivalent XXX_free (or XXX_close, XXX_clearup, or whatever) function, that the client code can call when finished with the pointer.
That way, you have a consistent, symmetrical API, in the sense that responsibility for the lifetime of a heap object is maintained in one place.
This approach is also amenable to more-complex resource freeing. For example, if the pointer that gets returned is to a dynamically-allocated struct that in turn has members that point to dynamically-allocated memory, the entire cleanup procedure can be hidden/abstracted from the client code.
You've tagged your question C. In C, it's very commonplace, e.g. fopen returning FILE * which must later be deallocated by calling fclose.
If you meant to tag it C++, then it's more complicated. Older codebases (mid-1990s and earlier) frequently passed around naked pointers to objects. Whole commercially supported libraries were based on that pattern (Borland's OWL, Microsoft MFC).
If you need to do this, it's common practice to provide your own "free" function that takes your allocated pointer and free it. This prevent user to use an incompatible free implementation that would corrupt memory.
You'll find examples of both methodologies: either a function allocating memory and returning a pointer, or a function accepting a pointer to already allocated space.
As long as the interface is clearly documented and followed, there are positives and negatives for both. For example, as many other people have mentioned, a library providing an allocation function typically should provide a delete function. As you, the client, don't know what method was used to allocate memory in that fancy function, you (the client) don't know what method should be used to destroy it.
On the other hand, the logic can be more complex when you need to worry about allocation of storage, passing that off to something that may or may not perform the work expected, and then determining if that storage is still pertinent, etc. Depending on the use of the memory, hiding away the allocation details could help encapsulate some optimization of it as well.
Short answer is: it's up to you. The really wrong way to go is to pick something and either be inconsistent or unclear in the interface.
It was, and is still common, as it's pretty much the only way to handle libraries built against different runtimes on certain operating systems. For example, on Windows, sharing multiple VC++ runtime libraries in a single executable typically will only work correctly if the libraries are responsible for all of their own memory management, including both the allocation of the objects as well as the disposal. shared_ptr and similar tools actually can cause issues in that case.
That being said, typically, the function name and/or documentation (when done correctly) would make it obvious this was happening. It was also common to have a corresponding DeleteXXX() function to handle the free call.
Generally you would only return a pointer from an explicit create_blah() function
More common is to pass in a pointer (to a pointer), which if it is null was allocated by the function.
Actually a better idiom (used by COM interfaces) is to require pointer creation at the caller before the point of the function call, and write a function that accepts a double pointer.
For example:
HRESULT CreateDevice(
[in] UINT Adapter,
[in] D3DDEVTYPE DeviceType,
[in] HWND hFocusWindow,
[in] DWORD BehaviorFlags,
[in, out] D3DPRESENT_PARAMETERS *pPresentationParameters,
[out, retval] IDirect3DDevice9 **ppReturnedDeviceInterface
);
So, the caller is responsible for creating the pointer and calling the allocation function, and so is more likely to remember to call the deallocation function (which in COM's case requires you call a ->Release() method on the COM object)
But I think adopting Creation/Destruction functions, combined with passing double pointers, is a better way to remind the recipient of a heap allocated object to clean up after using the object.
I agree with Oli that Create/Destroy functions are much more symmetrical and the existence of the Destroy function should turn the API user onto the fact that these objects he gets from the Create functions won't just disappear on their own, and they (Destroy fcns) need to be called.

How do I tell if I'm leaking COM objects?

I'm writing some code that makes (relatively simple) use of COM, calling AddRef() on some objects and Release()ing them later. Other than just checking the code really thoroughly, is there a way I can check to see if I'm leaking COM objects everywhere?
(I can't use reference counted IBlahBlahPtrs because I need to pass the objects to a set of APIs who don't know what a COM is, and so don't understand the whole "reference counting pointers" thingy - they pass the pointer around like a token.)
Thanks!
It is no different from checking for leaks in any C or C++ code. Use <crtdbg.h> to detect leaks, the MSDN library article is here. You'll get a leak report for the class factory if there were not enough IUnknown::Release() calls.
Reference counting interface pointers is a hard COM requirement, you cannot just shrug it off. If the client code doesn't do it then you'll have to take care of it yourself before you pass a pointer to that code. Knowing when the pointer is no longer in use is of course the trickier issue.
If you use the CrtDebug DEBUG_NEW to allocate your objects, you'll get an automatic dump of all leaked objects at exit time (basically, all memory that is not freed), along with the file name and line where the memory was allocated.
Based on our conversation in comments, I'd say you could do the following:
Use smart pointers (i.e., IBlahBlahPtr) to create and manage COM objects in your own code.
Maintain a collection of smart pointers representing your caller's references to the pointers that you've passed upwards. Every time you hand a new COM pointer over to your caller, put its smart pointer in the collection.
If your caller relinquishes a COM pointer somehow (by, say, passing you the COM pointer token in some kind of "release" function), then look up its smart pointer in the collection and remove it. If that smart pointer (representing the caller's now-defunct reference to the object) is the only remaining holder of a reference count on the object, then destruction will occur as desired.
If your caller passes you a COM pointer in a non-relinquishing way, you can wrap a new smart pointer object around the raw pointer value for the duration of the call, just so that your use of smart pointers within your own code is consistent. It's fine for multiple smart pointers to refer to the same COM object.
Various tools will check for you. BoundsChecker does. I think, but am not 100% sure, that AppVerifier does (it has the added benefit of being free).