Expects/Ensures do not trigger breakpoints??

Hi Guys,

I'm learning about pre and post conditions and how to apply them. I am told the Expect/Ensures macros from GSL are the way to go. As far as I understand these macros are supposed to trigger a breakpoint and "lead" you to the origin of the error, however instead of doing this they simply give me a debug error with no really tangible information! Am I doing something wrong here? Thanks!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <string>
#include <gsl/gsl>
using namespace std;

inline void empty_string_check(const string* const p) {
	Ensures(*p != "");
}

int main() {
	empty_string_check(new string(""));
	
	string x;
	getline(cin, x);
	return 0;

}
I'm learning about pre and post conditions and how to apply them.

okay

I am told the Expect/Ensures macros from GSL are the way to go.
er, not sure how this relates to previous statement, but okay...
Edit: never mind; precondition and postcondition (one word, not two) -- something that must always be true before or after a piece of code.

See this answer on defining GSL_THROW_ON_CONTRACT_VIOLATION before your #include (line 3) ; might give you more info depending on your OS https://stackoverflow.com/questions/36349523/ensures-guideline-support-library

The problematic line number might already be obvious, though. Hopefully that lib gives you some info about local vars at the time of the crash too.
Last edited on
found the public file for gsl_assert from Microsoft's github, which contains definitions for expects/ensures. Made a little project at https://repl.it/@icy_1/QuarterlyOldlaceHypotenuse to play around with it.

As per the comments in gsl/gsl_assert file, the default behavior is simply to terminate, but once the define is in play you get a file and line number. Then it's up to you to automatically breakpoint when uncaught C++ exceptions are thrown. In newer Visual Studio s, it's under Debug->Windows->Exception Settings, and then check off "C++ Exceptions".

btw, I think this would be considered a precondition -- checking the string for emptiness, etc, before doing something with it. For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>

#define GSL_THROW_ON_CONTRACT_VIOLATION 1
#include "gsl/gsl_assert"

using namespace std;

void FirstTwoCharacters(const string& s)
{
    Expects(!s.empty() && s.size()>=2);
    cout << s[0] << '\n' << s[1] << '\n';
}

int main() 
{
    string s("12");
    FirstTwoCharacters(s);

    string bad("a");
    FirstTwoCharacters(bad);

    return 0;
}
Last edited on
Thanks icy!
Topic archived. No new replies allowed.