Re: Initialization -- One Stage or Two Stage
From: Jonathan Mcdougall (jonathanmcdougall_at_DELyahoo.ca)
Date: 01/04/05
- Next message: Howard: "Re: Where Can I download Cfront from ?"
- Previous message: Keith Thompson: "Re: compile C programs with UNIX system calls (= Unix Programs??)"
- In reply to: Brian Folke Seaberg: "Initialization -- One Stage or Two Stage"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 4 Jan 2005 16:02:26 -0500
"Brian Folke Seaberg" <bseab1024se@aol.com> a écrit dans le message de news:
20050104145324.21909.00002905@mb-m06.aol.com...
>I have been examining the documentation for a class library written in C++.
>
> It seems that most of the classes in that library use two stage
> initialization.
> Objects are not ready for use after construction. Objects are ready for
> use
> only after post-constructor initialization functions have been executed.
>
> I prefer one stage initialization. I believe that upon completion of
> object
> creation an object should be in a valid state and therefore immediately
> usable.
>
>
> Are there practical reasons to split initialization into two steps?
>
> What does one gain by doing so?
If you don't have the information necessary for the object's construction,
you need to postpone it. One way is to use the heap to construct the object
as necessary but there are circumstances where this is not preferrable
(stack based objects are usually more "efficient"). The only way left is
two-stage initialization.
The problem associated with it is that the object is in an invalid state.
Each function must make sure the object is valid, which requires these
functions to throw, to return an error or set a flag. This is a pain for
the library and the user, but it may be the only way.
A solution would be to provide both approaches, by providing an default
constructor for two-stage intialization plus a create() function and a
constructor with arguments for direct initialization. I think Microsoft
uses that a lot in its MFC.
Jonathan
- Next message: Howard: "Re: Where Can I download Cfront from ?"
- Previous message: Keith Thompson: "Re: compile C programs with UNIX system calls (= Unix Programs??)"
- In reply to: Brian Folke Seaberg: "Initialization -- One Stage or Two Stage"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|