I wanted to know if the following code is well formed
if ( nChildLines == 0 )
{
nChildLines = 1;
Tag tempTag = attachmentlines.tag();
cfgChildLines = &tempTag;
}
Here, tampTag is some object. And cfgChildLines is a scoped pointer to that object declared outside of the ‘if’ block.
Now my question is, when the ‘if’ block completes, does tempTag get destructed? And if so, is the usage of the ‘cfgChildLines’, which points to tempTag, valid past the end of the if block?
Important to remember that taking an address in C++ does NOT guarantee any protections that that address continues to point to something valid. There’s no reference counting built into the language (thats why we had to invent scoped_ptr/shared_ptr/etc).
Keeping that in mind, we can look in more detail at your situation:
tempTagis an automatic variable and gets destroyed at the end of the scope it was created it. The address you took therefore will point somewhere on the stack to a destroyed object outside this scope. Since you assigned to a scoped_ptr, and scoped_ptr assumes it can destroy the object through delete, from the documentation(emphasis mine)
So you’re violating scoped_ptr’s interface and you’re going to have some undefined behavior once the scoped_ptr is deleted.
If you really need tempTag in a larger scope, then just declare it in the larger scope you need it in and don’t use scoped_ptr.
Another way to think about it: When you create a dynamically allocated object, you take ownership of its lifetime. You manually create and destroy the thing. Therefore you can pass this ownership to another object, such as a scoped_ptr which can manage things for you. In contrast, variables created on the stack will be automatically allocated and deallocated — the rights to create and destroy are held entirely by the call stack and you can’t give those rights to yourself or someone else (ie scoped_ptr). You can only strategically place those variables in a place that correctly scopes the variable so that the automatic, stack-based lifetime corresponds with how you intend to use the thing.