Bug Spotting: Smart pointers and parameter evaluation order - Dave's Blog

Search
My timeline on Mastodon

Bug Spotting: Smart pointers and parameter evaluation order

2011 Oct 19, 5:58
The following code works fine. I have a ccomptr named resolvedUri and I want to update its hostname so I do the following:
        CreateIUriBuilder(resolvedUri, 0, 0, &builder);
builder->SetHost(host);
builder->CreateUri(0xFFFFFFFF, 0, 0, &resolvedUri);


But the following similar looking code has a bug:
    ResolveHost(resolvedUri, &resolvedUri);


The issue is that doing &resolvedUri gets the address of the pointer but also clears out the pointer due to the definition of my smart pointer class:
    operator T**()  
{
T *ptrValue = mPtrValue;
mPtrValue->Release();
mPtrValue = NULL;
return &ptrValue;
}


In C++ there’s no guarantee about the order in which parameters for a function or method are evaluated. In the case above, &resolvedUri clears out the ccomptr before evaluating resolvedUri.Get() and so ResolveHostAlias gets a nullptr.

An interesting and related thread on stack overflow on undefined behavior in C++.
PermalinkCommentsc++ technical bug programming smart-pointer cpp
Older Entries Creative Commons License Some rights reserved.