How C++ avoids implicit conversion operators
This article mainly introduces "how C++ avoids implicit conversion operators". In daily operation, I believe many people have doubts about how C++ avoids implicit conversion operators. Xiaobian consulted all kinds of data and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts of "how C++ avoids implicit conversion operators". Next, please follow the editor to study!
C.164: avoid implicit conversion operators
Reason (reason)
Implicit conversions can be important (for example, converting double to int), but often lead to unexpected results (for example, converting String to C-style strings).
Note (Note)
Explicit naming conversions are preferred until requirements that must be taken into account are found. We use "must pay attention to the needs" to express the reasons that are very essential in the application field (such as integer to plural conversion) and often encountered. Do not introduce implicit conversions (through conversion operators or non-explicit constructors) because of small convenience.
Example (sample)
Struct S1 {
String s
/ /...
Operator char* () {return s.data ();} / / BAD, likely to cause surprises
}
Struct S2 {
String s
/ /...
Explicit operator char* () {return s.data ();}
}
Void f (S1 S1, S2 S2)
{
Char* x1 = S1; / / OK, but can cause surprises in many contexts
Char* x2 = S2; / / error (and that's usually a good thing)
Char* x3 = static_cast (S2); / / we can be explicit (on your head be it)
}
Unexpected, potentially damaging implicit conversions can occur at any time and are difficult to detect.
S1 ff ()
Char* g ()
{
Return ff ()
}
The string object returned by ff () is destroyed before the returned pointer is used.
Enforcement (implementation recommendations)
Prompt all conversion operators.
At this point, the study of "how C++ avoids implicit conversion operators" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!