Ensures() - guideline support library
Asked Answered
T

1

8

I am trying to understand how to use Ensures() in code. As given in the example, if I tried using Ensures() as follows...

int main(void)
{
    int result = 0;
    // Some calculation
    Ensures(result == 255);
    return 0;
}

If the result variable is not equal to 255, the program crashes with the following output "terminate called without an active exception". My question is how to use Ensures() properly?

Tasse answered 1/4, 2016 at 6:33 Comment(1)
If you std::terminate is called in your example, then it works as is should.Gare
G
14

Are you using the Microsoft GSL implementation? Then if you check the gsl_assert.h header file you will see that if GSL_TERMINATE_ON_CONTRACT_VIOLATION is defined (which is default) then Ensures will call std::terminate which will give you the error you get.

If you want an exception to be thrown (with file and line-number information) then you need to define GSL_THROW_ON_CONTRACT_VIOLATION before including the GSL.

As for if you're using Ensures properly, then yes you are.


Updates on 2021

GSL_TERMINATE_ON_CONTRACT_VIOLATION is removed, always calling terminate().

Ginnygino answered 1/4, 2016 at 6:48 Comment(4)
Thanks, for the reply, will check the header.Tasse
I am not using MS GSL. I tried using MS GSL with Visual Studio 2013. But was getting "fatal error C1001: An internal error has occurred in the compiler".Tasse
As per your suggestion, I went into the "gsl-lite.h" and modified the # define gsl_CONFIG_THROWS_FOR_TESTING 0 to # define gsl_CONFIG_THROWS_FOR_TESTING 1. Now I am getting exception which i can catch it. Thanks.Tasse
As decided by the Core Guideline authors the MS GSL lately removed GSL_THROW_ON_CONTRACT_VIOLATION and now always std::terminates. But... there is still a discussion ongoing because the Core Guidelines seem to be inconsistent about the behaviour of Expects.Gare

© 2022 - 2024 — McMap. All rights reserved.