| re: How to add and call a do-nothing non-default constructor?
Ng Hun Yang wrote:[color=blue]
> Victor Bazarov wrote:
>[color=green][color=darkred]
>>>I want SomeClass's constructor to skip initializing a_, so I changed it
>>>to:
>>> SomeClass(): a_(Integer(Integer::NoInit())) { }[/color][/color]
>
>[color=green]
>>Why the unnecessary intermediary? Couldn't you just write
>> SomeClass() : a_(Integer::NoInit()) {}
>>?[/color]
>
>
> hmm, you're right! I forget a_(...) itself is a constructor call!
>
> SomeClass() : a_(Integer::NoInit()) {}
>
> works!
>
> (Looks like I have to remove C++ from my resume. ;-))[/color]
If folks did that every time they use an extra copy, we'd probably have
less than a hundred of people with C++ on their resumes. :-)
[color=blue]
> But suppose now I convert this to the named constructor idiom:
> class Integer {
> private:
> enum NoInitT { NoInitV };
> explicit Integer(NoInitT) { }
>
> public:
> Integer(): v_(0) { }
> Integer(int v): v_(v) { }
> static Integer NoInit() { return Integer(NoInitV); }
>
> private:
> int v_;
> };
>
> class SomeClass {
> public:
> SomeClass(): a_(Integer::NoInit()) { }
>
> private:
> Integer a_;
> };
>
> Still the same thing, right?
>
> However, NoInit() creates a temporary (uninitialized) return object
> which is then copied to a_. Can't the compiler initialize a_ in-place?
>[/color]
I might be able to, or it might not. There is no requirement in the
Standard that the compiler does so. The Standard allows, however, to
omit the copying and initialise an object directly, even if the copy
constructor has side effects. So, set your optimization levels high
and hope for the best :-)
V |