D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 7182 - Call const or immutable member functions from class invariant
Summary: Call const or immutable member functions from class invariant
Status: RESOLVED INVALID
Alias: None
Product: D
Classification: Unclassified
Component: dmd (show other issues)
Version: D2
Hardware: Other All
: P2 enhancement
Assignee: No Owner
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2011-12-29 06:17 UTC by Taco
Modified: 2017-06-26 14:51 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Taco 2011-12-29 06:17:44 UTC
The following code yields an error:

class A
{
public:
    int f() const
    {
        return 5;
    }

protected:
    invariant()
    {
        assert (f() == 5);
    }
}

"Error: cannot call public/export function f from invariant"

Why? f() is const and cannot change the state of an instance of A. Invariant checks are redundant around const/immutable public member functions.

What if 'this' was passed to the member function?
Comment 1 Infiltrator 2014-03-19 22:38:31 UTC
I think that the issue would instead be with the fact that public functions (f() in this case) call invariant() before and after they run, which would result in an infinite loop.

I therefore think that this should be closed as INVALID.  Any of you big guns want to weigh in on this?
Comment 2 Vladimir Panteleev 2017-06-26 14:51:19 UTC
(In reply to Infiltrator from comment #1)
> I think that the issue would instead be with the fact that public functions
> (f() in this case) call invariant() before and after they run, which would
> result in an infinite loop.

Pretty sure your explanation is correct.

Although one may argument in favor of making const methods not cause invariant checks, that would mean that e.g. getters are no longer protected by invariants, should something modify the object's state into an invalid one directly (e.g. by writing to fields).