Advantage of gsl assert vs assert in c++?
Asked Answered
H

1

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;
}
Heliotaxis answered 29/5, 2019 at 12:35 Comment(4)
Check this question.Phthisic
I got it, thanks for sharing:)Heliotaxis
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).Heliotaxis
Off-topic, but using namespace std; is considered bad practice.Irreligious
A
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.

Actable answered 29/5, 2019 at 13:31 Comment(1)
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.Handcuff

© 2022 - 2024 — McMap. All rights reserved.