_bstr_t behaviour (how it should work in ANSI C++)

P

Paul Drummond

Hi,

I hope I am not posting in the wrong place! I have posted to the MFC
group but thought I might get more of a response here as the question
is C++ specific. If I am wrong to post here or violating some rule
please let me know and I promise I won't do it again :)

I am using MFC/COM _bstr_t() in Visual C++ 6.0 and I am insterested to
know what constructors get called when the following call is made:

int main()
{
_bstr_t b = _bstr_t("Hello world");
return 0;

}

I realise VC++ is old and not standards-compliant, so forgetting that
for a moment I just want to make sure what I think should happen is
what would happen in ANSI C++!

I would expect the constructor which accepts a const char* would be
called which would return a temporary object then the copy-constructor
would be called to assign the temporary to "b".

When I run the debugger, the const char* constructor is called but no
copy-constructor! At first I thought this may be a compiler
optimization of some sort, or maybe some obsure feature of Visual C++
6.0 so I made a dummy class to test my theory and I was correct - the
copy constructor is called for my test class, so why not for _bstr_t?
 
B

Bronek Kozicki

Paul Drummond said:
I am using MFC/COM _bstr_t() in Visual C++ 6.0 and I am insterested to
know what constructors get called when the following call is made:

_bstr_t has nothing to do with MFC nor ATL. It belongs to "builtin COM
support", or more acurately set of headers distributed with the
compiler, which are used by some compiler extensions that we are not
going to discuss here.
_bstr_t b = _bstr_t("Hello world");
I would expect the constructor which accepts a const char* would be
called which would return a temporary object then the copy-constructor
would be called to assign the temporary to "b".

you are almost right. However C++ standard has an extra clause (12.8)
that allows (but does not require) temporary object to be entirely
eliminated when it's being copied around. Even if it changes behaviour
of the program in respect to copy constructor calls. This is why you
shouldn't depend on copy constructor being called, and this is why the
only thing copy constructor may do reliably is to perform a copy.
copy constructor is called for my test class, so why not for _bstr_t?

because compiler decided that it may optimize-away temporary object of
_bstr_t type in this context. Next version of the compiler might do this
to your type, and it is standard conforming behaviour


B.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,564
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top