Pre-condition and Post-condition in C++

Ok, let’s check the method that realize DbC in standard C++. About realizing pre-condition, anybody think that an assert in a first part of function is effectual. That’s right. And, it is also correct method about assert.

Then, do you realize post-condtion? You can not realize post-condition of DbC by an assert in a end part of function because post-condition is must executed after return code. And, you’ll hope to write all conditions in a first part of function. This page that this site introduced yesterday answers that question well. You can use ‘Destractor’ to realize post-condition.

void foo()
{
struct Sentry
{ Sentry() { …preconditions… }
~
Sentry() { …postconditions… }
}
sentry;
implementation
}

Destractor is called when the instance goes out of scope. Therefore, You can check post-condition after the end of function by this method.

Advertisements
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s