8000 Add note about implicit conversions · misgeatgit/cppbestpractices@6b8144b · GitHub
[go: up one dir, main page]

Skip to content

Commit 6b8144b

Browse files
committed
Add note about implicit conversions
1 parent fbcdfa6 commit 6b8144b

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

03-Style.md

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -318,11 +318,23 @@ More detailed, you should keep these things in mind:
318318
* Do not overload exotic operators such as ~ or %.
319319
* [Never](http://stackoverflow.com/questions/5602112/when-to-overload-the-comma-operator?answertab=votes#tab-top) overload `operator ,` (the comma operator).
320320
* Use `operator >>` and `operator <<` when dealing with streams. For example, you can overload `operator <<(std::ostream &, MyClass const &)` to enable "writing" you class into a stream, such as std::cout or an std::fstream or std::stringstream. The latter is often used to create a textual representation of a value.
321-
* There are more common operators to overload [described here](http://stackoverflow.com/questions/4421706/operator-overloading?answertab=votes#tab-top).
322-
* Do not use conversion operators except `operator bool` for values that clearly have a "true" or "false" state, or "right" or "wrong" so that you can write `if (myValue)` even if myValue is of a custom class.
321+
* There are more common operators to overload [described here](http://stackoverflow.com/questions/4421706/operator-overloading?answertab=votes#tab-top)
323322
324323
More tips regarding the implementation details of your custom operators can be found [here](http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html).
325324
325+
## Avoid Implicit Conversions
326+
327+
### Single Parameter Constructors
328+
329+
Single parameter constructors can be applied at compile time to automatically convert between types. This is handy for things like `std::string(const char *)` but should be avoided in general because they can add to accidental runtime overhead.
330+
331+
Instead mark single parameter constructors as `explicit`, which requires them to be explicitly called.
332+
333+
### Conversion Operators
334+
335+
Similarly to single parameter constructors, conversion operators can be called by the compiler and introduce unexpected overhead. The should also be marked as `explicit`.
336+
337+
326338
## Consider the Rule of Zero
327339
328340
The Rule of Zero states that you do not provide any of the functions that the compiler can provide (copy constructor, assignment operator, move constructor, destructor, move constructor) unless the class you are constructing does some novel form of ownership.

0 commit comments

Comments
 (0)
0