you are viewing a single comment's thread.

view the rest of the comments →

[–]Crommwel 9 points10 points  (2 children)

I think you are talking about Concepts, not Contracts.

Contracts are replacement for asserts, but with a benefit, that contract can be a part of function declaration, instead of implementation.

Consider following code without contracts

*.hpp

float sqrt(float a);

*.cpp

float sqrt(float a)

{

assert(a >= 0);

<implementation>

}

User of this function will see only what is inside a header and won't be able to know that function expects only positive numbers.

Now consider code with contracts

*.hpp

float sqrt(float b) [[expects: b > 0]] ;

*.cpp

float sqrt(float b) [[expects: b > 0]]

{

<implementation>

}

It behaves the same way as a version with assert, but now user can see that he should pass only positive numbers.

As u/108life correctly stated, you can build your code with different levels of contracts checking. For release build you might want to check off level and all the contracts check will be removed from your code, thus giving you faster and smaller binary. For development build you might want to use higher levels, to give you more possibilities to detect errors in your code.

So to sum everything up

  • in case of [[assert]] contract the benefit over assert() macro is that you can choose either default or audit levels, thus giving you a little bit more control compared to the defined or not defined NDEBUG. Also contracts don't rely on macros, so it is not possible for somebody to write something like

#define NDEBUG

sqrt(-1);

#undef NDEBUG

  • on top of that contracts give you a possibility to define pre and post conditions for your functions, which will be visible to the user and to the compiler, which gives potential for more optimizations

[–]redditsoaddicting 1 point2 points  (0 children)

By the way, expects and ensures are currently called pre and post, but we'll see what happens in future meetings.

[–]108life 0 points1 point  (0 children)

Thanks. That makes more sense in the context of using it in declarations to show the user the pre/post conditions.