Re: Using Reference of Pointers
niklasb_at_microsoft.com
Date: 02/17/05
- Previous message: Jonathan Turkanis: "Re: c++ system call invoke perl running visual c++ 6.0"
- In reply to: V. de Bellabre: "Using Reference of Pointers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 17 Feb 2005 12:03:50 -0800
V. de Bellabre wrote:
> Some of my c++ class are complex and use many pointers so I decided
to
> force initialisation of objects through their static function Create,
> which has a parameter IN-OUT that will contain the instance of the
> created object.
An alternative would be to simply have your Create function return
a pointer. OUT parameters have their place, but all else being equal,
simply returning a value is usually more clear.
> typedef class Texture* PTEXTURE;
> // With this, PTEXTURE& is a reference of a pointer to Texture
Personally, I think hiding a pointer behind a typedef like this
obfuscates more than it clarifies. Yes, I know the Windows header
files do this all the time, but I suspect that's a holdover from
the bad old 16-bit days of __near and __far pointers.
> class Texture:
> {
> protected:
> Texture( void ){} // Constructor, do nothing, use Create
Is Texture meant to be derived from? If so, you should probably
add a virtual destructor. If not, the ctor should be private
instaed of protected.
> public:
> static void Create( PTEXTURE& ); // PTEXTURE& is a reference of a
> pointer to the texture to create
Or:
static Texture* Create();
Problem solved, and no need for reference-to-pointer.
> // Implementation of the Create Function
> void Texture::Create( PTEXTURE& pTexToCreate )
> {
> pTexToCreate = new Texture; // memory alloc
>
> // Some init...
>
> if( badInit )
> {
> delete pTexToCreate;
> pTexToCreate = NULL;
> }
> }
The code above should work as you intended. The only thing I
can think of is there's undefined behavior somewhere else in
code you snipped. You might try taking the stripped-down code
you posted and edit it to be actually compilable, then run it
to see if the problem still manifests.
As a matter of style, I'd prefer to see Create return a
pointer. There's no need for an OUT or IN/OUT parameter here.
Better yet, why not do the initialization in the ctor as C++
is meant to be used? If initialization failed, the ctor would
throw an exception. (My guess is you're using a factory method
instead because you want to return NULL instead of throwing an
exception on failure.)
> // A small example of how I use this
> void main( void )
> {
> PTEXTURE pMyTexture;
> Texture::Create( pMyTexture );
> if( pMyTexture == NULL )
> // Error creating the texture
> }
The return value of main must be int. The above is not legal
C++, although some compilers accept it.
- Previous message: Jonathan Turkanis: "Re: c++ system call invoke perl running visual c++ 6.0"
- In reply to: V. de Bellabre: "Using Reference of Pointers"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|