Re: Constructor denial?

Tech-Archive recommends: Repair Windows Errors & Optimize Windows Performance



Or you can supply your own 'new' operator for that class. in that case you
can use a flag or an exception in your constructor to signal that
construction has failed, and let the 'new' operator return a NULL pointer.

kind regards,
Bruno.


"Tamas Demjen" <tdemjen@xxxxxxxxx> wrote in message
news:%23kJEY6WEGHA.916@xxxxxxxxxxxxxxxxxxxxxxx
> Peter Oliphant wrote:
>
>> I'm guessing it's not possible to actually just return 'nullptr' in a
>> construction attempt like 'malloc' does...
>
> You can add a static member to the class, and call that instead of the
> constructor. It doesn't require a separate factory class. You can
> optionally make the constructor private, if you want to force your own
> function instead.
>
> class C
> {
> public:
> C();
> static C* TryCreate()
> {
> try
> {
> C* c = new C;
> return c;
> }
> catch(...)
> {
> return 0;
> }
> }
> };
>
> You can apply the same idea to C++/CLI. It's not that cumbersome, but I
> don't see why you prefer nullptr to an exception. If construction fails,
> that's almost always an error, and therefore the exception is valid.
>
> Optionally, you can set a failed flag in the constructor, and add a bool
> IsValid() const member function. It's very good for classes that can fail
> for a valid reason, which as a FileStream.
>
> Tom


.



Relevant Pages

  • Re: Go ahead. Stop programming. This ensures you from any mistakes.
    ... Creation is rolled back by exception. ... Indeed, it can't be, because the constructor could have assigned ... Hence "along with a success flag". ... I use plenty of non-memory resources, but don't rely on the GC to ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: DbC & Exceptions & Style
    ... exception. ... Different ways the constructor can fail ... to avoid writing code that converts GUI data into objects, ... All domain objects must now provide a default constructor. ...
    (comp.object)
  • Re: Controlled types and exception safety
    ... >> propagate an exception. ... >> For an Adjust invoked as part of an assignment operation, ... But a user-defined constructor is ... a user-defined constructor has just turned on the ...
    (comp.lang.ada)
  • Re: is such exception handling approach good?
    ... There is nothing wrong with throwing from constructor. ... It may be a good design, it may not be a good design from user's point ... resource API to free-up the resource on exception. ... change something - that is not initialization. ...
    (microsoft.public.vc.language)
  • Re: Question concerning object-oriented programming
    ... constructor the inspectof the state fails to verify key ... Better yet the constructor could throw an exception. ... opposed to stateless) object can know if it is in an invalid state. ...
    (comp.programming)