1. In some cases, explicit can effectively prevent errors or misunderstandings caused by implicit conversions of constructors.
2,
Explicit only applies to constructors and is used to suppress implicit conversions. For example:
Class {
A (int );
};
Int Function (A );
When Function (2) is called, type 2 is implicitly converted to type. This situation is often not the result that programmers want. To avoid it, you can write it like this:
Class {
Explicit A (int );
};
Int Function (A );
In this way, when Function (2) is called, the compiler will give an error message (unless the Function has an overloaded form that uses int as the parameter ), this avoids errors without the programmer's knowledge.
3. The explicit keyword of the constructor effectively prevents implicit conversion from a "Bare" pointer to the auto_ptr type.
4. Unlike the reference counting smart pointer, auto_ptr requires its full possession of the "Bare" pointer. That is to say, a "Bare" pointer cannot be owned by more than two auto_ptr at the same time. Therefore, during the copy construction or value assignment operation, we must make special processing to ensure this feature. The auto_ptr method is "ownership transfer", that is, the source object to copy or assign values will lose ownership of the "Bare" pointer. Therefore, unlike the general copy constructor, the assign function is different, the copy constructor of auto_ptr. the parameter of the value assignment function is referenced rather than often.