This compiles, but I’ve never seen it in any other code. Is it safe?
Testclass():sources(new int[32]){}
Instead of:
Testclass(){
sources = new int[32];
}
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Use:
This is using member-initialization-list which is the preferred way to initialize members.
By “safe” or “okay” you probably meant, whether it is exception-safe? What if
newthrows the bad_alloc exception?Well, in that case, the destructor will not be called, because the object is not fully-constructed, as constructor-body is not executed. There may be a resource leak if you’ve acquired any resource in the initialization list.
Consider this,
If
new Huge[10000]throws an exception, the memory allocated tointswill leak!In such cases, function-try-block can be useful. See these:
If you think about this problem of exception-safety, you will soon realize that if a class manages just one resource, then the life will be easier. If a single class manages more than one resource, then you wouldn’t be able to decide which one threw an exception in the member-initialization-list, and consequently, you wouldn’t be able to decide which one is to be deallocated in the
catchblock of function-try-block. A resource leak is destined.However, if a class needs more than one resource, then first you encapsulate each of the different type of resource in a class, and declare objects of these resource-managing class as a member of your class.