[Issue 5058] invariant() should not be called before opAssign()

d-bugmail at puremagic.com d-bugmail at puremagic.com
Mon Nov 1 12:48:33 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=5058



--- Comment #8 from Steven Schveighoffer <schveiguy at yahoo.com> 2010-11-01 12:47:25 PDT ---
I look at invariants differently than you do I guess.  To me, an invariant is a
self-checking mechanism that says "Every public function is going to leave this
item in a sane state, and therefore, every public function should expect this
to be in a sane state".  It should not be possible for a user who is using a
struct to break an invariant unless they violate the type system.

To me, T.init should always pass the invariant because the user is allowed to
declare:

T t;

And this is guaranteed by the language.  Therefore, it's always part of the
public interface.

In other words, invariants are more to protect the user against the struct
misbehaving, not to protect the struct against the user misbehaving.

For example, a poorly constructed invariant:

struct S
{
  public int i;
  invariant()
  { assert(i == 0); }
}

This looks to me like what you are doing -- ensuring the user has not mucked
with your struct data.  What an invariant really should do is ensure that the  
struct has not mucked with the struct data.  If the user does it, they do so at
their own risk.

It would be like expecting the invariant of a class to assert the reference is
not null first.

And really, what is the difference between a segfault and an assert error? 
Both should halt execution, and both should print out a valid stack trace.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list