comp.lang.ada
 help / color / mirror / Atom feed
From: Jacob Sparre Andersen <jacob@jacob-sparre.dk>
Subject: Re: Unknown constraints and type composition
Date: Sun, 08 Jul 2018 15:53:44 +0200
Date: 2018-07-08T15:53:44+02:00	[thread overview]
Message-ID: <87k1q5ltp3.fsf@adaheads.home> (raw)
In-Reply-To: pfvhu2$e4a$1@gioia.aioe.org

J-P. Rosen wrote:

> Even better, the default can be a raise expression (or a function that
> raises an exception for pre-2012), so no uninitialized object can be
> created. This is a run-time check, but a decent compiler would warn
> you at compile time.

This does not give a warning at compile time with FSF GNAT 8
(Debian/sid), nor with GNAT CE 2018, but you get the correct run-time
error with both compilers:

   private with Ada.Strings.Unbounded;
   
   package Initialisation_Required is
   
      type Instance is private;
   
      function Create (Name : in String) return Instance;
   
   private
   
      type Instance is
         record
            Name : Ada.Strings.Unbounded.Unbounded_String := raise Constraint_Error with "Uninitialised object.";
         end record;
   
   end Initialisation_Required;

   package body Initialisation_Required is
   
      function Create (Name : in String) return Instance is
      begin
         return R : Instance do
            R.Name := Ada.Strings.Unbounded.To_Unbounded_String (Name);
         end return;
      end Create;
   
   end Initialisation_Required;

   with Initialisation_Required;
   
   procedure Demo is
      O : Initialisation_Required.Instance := Initialisation_Required.Create (Name => "Hello");
   begin
      O := Initialisation_Required.Create (Name => "Hello");
   end Demo;

Another problem with this is that you can't wait until you leave your
internal constructor function, before the initialisation has to happen.

With the example above, you get your exception already at "return R :
Instance do", which isn't what we want.  (Easy to work around, but
something you should be aware of.)

Greetings,

Jacob
-- 
"Sleep is just a cheap substitute for coffee"

  parent reply	other threads:[~2018-07-08 13:53 UTC|newest]

Thread overview: 9+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2018-06-14 15:37 Unknown constraints and type composition Alejandro R. Mosteo
2018-06-14 16:19 ` Dmitry A. Kazakov
2018-06-14 16:58 ` sbelmont700
2018-06-14 17:53 ` Jeffrey R. Carter
2018-06-15  5:13   ` J-P. Rosen
2018-06-15  9:34     ` Alejandro R. Mosteo
2018-07-08 13:53     ` Jacob Sparre Andersen [this message]
2018-06-14 21:28 ` Randy Brukardt
2018-06-15  9:37 ` Alejandro R. Mosteo
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox