C + + is worth the effort for exceptional security __c++

Source: Internet
Author: User
Tags data structures mutex

20180319 C + + is worth the effort for exceptional security


Suppose you have a GUI menu that class uses to represent a background pattern. This class wants to be used in a multithreaded environment, so he has a mutex (mutex) for concurrency control (concurrency controls):
Class prettymenu{
Public
...
void Changebackground (std::istream& imgsrc);//Change background color
...
Private
Mutex mutex;//Mutex
image* bgimage;//the current background pattern
int imagechange;//Background image changed number of times
}


The following is a possible implementation of the Changeblackground function for Prettymenu:
void Prettymenu::changeblackground (std::istream& imgsrc)
{
Lock (&mutex);//Get Mutex
Delete bgimage;//get rid of old background images
++imagechange;//Modify the number of image changes
Bgimage = new Image (IMGSRC);//install a newer background image
Unlock (&mutex);//Free Mutex
}




From the "Exception security" point of view, this function is very bad. "Exception security" has two conditions, and this function does not satisfy any of them. When an exception is thrown, a function with exception security will:
1, do not disclose any resources. The above code does not do this because once "newimage (IMGSRC)" Causes an exception, the call to unlock is never executed, and the mutex is always held.
2, a strong guarantee: Do not allow data corruption. If "NewImage (IMGSRC)" Throws an exception, Bgimage is pointing to an object that has been deleted, Imagechange has been added, and no new images have been successfully installed.


Troubleshooting resource leaks You can use the import lock class as a way to ensure that the mutex is released in a timely manner:
void Prettymenu::changebackground (std::istream& imgsrc)
{
Lock M1 (&mutex);//
Delete Bgimage;
++imagechanges;
Bgimage = new Image (IMGSRC);
}


The exception security function (Exception-safe function) provides one of the following three guarantees:
1, the basic commitment: If the exception is thrown, the program in any thing still remain in a valid state.
2, if the exception is thrown, the state of the program does not change. Calling such a function requires the recognition that if the function succeeds, it is completely successful, and if the function fails, the program reverts to the state of "before the function is called."
3. Do not throw a guarantee: Promise never throws an exception, because they are always able to complete the functions they originally promised. All operations in a built-in type (such as ints, pointers, etc.) provide nothrow guarantees.








Consider the following functions, eg:


int dosomething () throw ();
This is not to say that dosomething absolutely does not throw an exception, but that DoSomething throws an exception, will be a serious error, there will be an unexpected function you are called.
If possible, provide nothrow assurances as much as possible, but for most functions, the choice often falls between the basic guarantee and the strong guarantee.


The following changes are almost enough to allow Changebackground to provide strong exception safety assurances:
Class prettymenu{
...
Std::tr1:;shared_ptr<image> Bgimage;
...
};
void Prettymenu::changebackground (std::istream& imgsrc)
{
Lock (&mutex);
Bgimage.reset (new Image (IMGSRC))//execution result with "new image"
Set Bgimage internal pointer
++imagechanges;
}




A generalized design strategy typically leads to a strong assurance that is well known to him, the strategy is called copy and swap, and the principle is simple:
Make a copy of the object (original) you intend to modify, and then make all necessary changes on that copy. If any modification action throws an exception, the original object remains in the unmodified state. After all the modifications are successful, the modified copy and the original object are replaced (swap) in an operation that does not throw an exception.


In fact, it is usually to put all the "subordinate object data" from the original object into another object, and then give the original object a pointer to the so-called implementation object (Implementation object, or copy). This technique is often called Pimpl idiom, for prettymenu, the typical wording is as follows:
struct pmimpl{
Std::tr1::shared_ptr<image> Bgimage;
int imagechanges;
};
Class prettymenu{
...
Private
Mutex mutex;
Std::tr1::shared_ptr<pmimpl> Pimpl;
};

void Prettymenu::changebackground (std::istream& imgsrc)
{
Using Std::swap;
Lock M1 (&mutex);//get replica data for mutex
Std::tr1::shared_ptr<pmimpl>
Pnew (New Pmimpl (*pimpl));

Pnew->bgimage.reset (New Image (IMGSRC))//Modify Copy
++pnew->imagechanges;
Swap (pimpl,pnew);//permutation (Swap) data, releasing a mutex
}


Attention:
1. The Exception security function (Exception-safe function) does not disclose resources or allow any data structures to corrupt even if an exception occurs. Such a function area is divided into three possible guarantees: basic type, strong type, no parabolic anomaly type.
2, "strong assurance" can often be implemented with Copy-and-swap, but "strong guarantee" is not all functions can be implemented or have display meaning.
3. The "Exception security guarantee" provided by the function is usually the highest in the "Exception security guarantee" of the functions that it invokes.


























Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.