10

I know the use of assert in C++. Wanted to know is there any difference between and any benefit(I think assert is costlier according as mentioned in https://www.learncpp.com/cpp-tutorial/7-12a-assert-and-static_assert/ so performance wise, are both same?) in using gsl_assert over assert? Why gsl_assert was added in gsl library since there is already assert support in c++(even though assert came from 'C', since we add #include<cassert> for using assert in C++)?

#include <iostream>
#include <gsl/gsl_assert>
using namespace std;

int main()
{
    int val;
    cin >> val;
    Ensures( val > 5 );
    return 0;
}
suresh m
  • 585
  • 5
  • 17
  • 3
    Check [this](https://stackoverflow.com/questions/36349523/ensures-guideline-support-library) question. –  May 29 '19 at 12:46
  • I got it, thanks for sharing:) – suresh m May 29 '19 at 13:08
  • but I wanted to know about the performance comparison of both, since assert is generally not used in the production build as mentioned in the above link(learncpp). – suresh m May 29 '19 at 13:22
  • 3
    Off-topic, but [`using namespace std;` is considered bad practice.](https://stackoverflow.com/q/1452721) – L. F. May 29 '19 at 13:25

1 Answers1

3

It's not a question of performance; it's a question of flexibility.

C assert

This just terminates (in debug builds) if the condition is true, and usually does nothing in release builds.

GSL contract check

Depending on configuration, this can:

  1. Throw an exception
  2. Terminate
  3. Do nothing
    • …except signal to the optimiser that we expect the condition to hold (if supported)

In some configuration modes, I suppose GSL's Expects and Ensures macros end up doing pretty much the same thing as assert. But not in all.

It's worth noting, though, that the GSL behaviour appears not to be dependent on build configuration (debug vs release). I guess (and I am only guessing) that, for performance-critical code, a sensible project maintainer would choose mode #1 or #2 in debug builds, and #3 (or possibly #2) in release builds.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 2
    As decided by the Core Guideline authors the MS GSL lately removed `GSL_THROW_ON_CONTRACT_VIOLATION` and now always `std::terminate`s. But... there is still a discussion ongoing because the Core Guidelines seem to be inconsistent about the behaviour of `Expects`. – Werner Henze Feb 28 '20 at 17:03