View Single Post
Old 1st January 2020, 23:07   #2  |  Link
LoRd_MuldeR
Software Developer
 
LoRd_MuldeR's Avatar
 
Join Date: Jun 2005
Location: Last House on Slunk Street
Posts: 13,248
Quote:
Originally Posted by stax76 View Post
Why is func1 100 times faster than the func2?

Code:
extern "C" {
	__declspec(dllexport) LPVOID __stdcall
	func1()
	{
		CmyInterface* pTest = new CmyInterface();
		LPVOID pMyInterface;
		pTest->QueryInterface(__uuidof(ImyInterface), &pMyInterface);
		return pMyInterface;
	}

        __declspec(dllexport) ImyInterface* __stdcall
        func2()
        {
            return (ImyInterface*) new CmyInterface();
        }
}
I see absolutely no reason why "func1" should be faster than "func2". Actually I would expect the opposite to be the case!

That is because both functions first create an instance of "CmyInterface", on the heap (via "new" operator). However, while "func2" simply returns the pointer to the created "CmyInterface" object, "func1" additionally calls QueryInterface() on the created "CmyInterface" object and then returns the pointer that was returned by QueryInterface(). So, clearly, "func1" does everything that "func2" does plus some additional work.

Needless to say that these function also do quite different things: "func2" simply casts the CmyInterface* pointer to an ImyInterface* pointer – which may be legit or not. Keep in mind that C/C++ happily casts a pointer to an incompatible type, if you ask it to do so, even though this would lead to undefined behavior at runtime! Conversely, "func1" returns whatever pointer is returned by CmyInterface::QueryInterface() – which totally depends on the implementation of the CmyInterface::QueryInterface() function. It is quite possible that CmyInterface::QueryInterface() simply returns "(ImyInterface*)this", but it could return a completely different pointer (to some other object) just as well!

BTW: I think you are missing error checking for the QueryInterface() call. Should this call fail, the value of pMyInterface (and thus the return value of "func1") will be undefined.

BTW²: I think "func1" may have a memory leak! Since "func2" simply returns the pointer to the created CmyInterface instance, it is clear that the caller will be responsible for destroying that object when no longer needed. But "func1" never returns the pointer to the CmyInterface instance – it only returns whatever pointer the call to QueryInterface() returned, which could be anything, and does not destroy the created CmyInterface object. So we probably have a leak here.
__________________
Go to https://standforukraine.com/ to find legitimate Ukrainian Charities 🇺🇦✊

Last edited by LoRd_MuldeR; 1st January 2020 at 23:41.
LoRd_MuldeR is offline   Reply With Quote