Skip to content

Changed operator bool to explicit rather than implicit conversion in Serial #16

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 17, 2019

Conversation

pratikpc
Copy link
Contributor

@pratikpc pratikpc commented Feb 1, 2019

In the file
SoftwareSerial.h and UART.h
If you were to notice that in every Serial based Class we have a function with the type
operator bool() { return true; }

By writing explicit, we can ensure that there is no form of implicit conversion or otherwise.
For further details view https://stackoverflow.com/questions/39995573/when-can-i-use-explicit-operator-bool-without-a-cast

This would ensure that bool b = Serial1; would not result in b getting a value

For example, comparing the following codes:-

struct T {
    operator bool() const { return true; }
};
int main()
{
    T t;
    bool B = t; // Okay
}

Does not result in an error due to an absence of explicit.
However, adding explicit we get an error that the conversion cannot be performed in the following sample.

struct T {
    explicit operator bool() const { return true; }
};
int main()
{
    T t;
    bool B = t; // error cannot convert t from bool
}

An Operator bool with explicit would render it compatible with only these statements

For example

while(Serial);
if(Serial)
for(;Serial;)

CONSTEXPR

Further, I have marked these statements as constexpr given they indeed are constant compile time expressions and their values will not change dynamically at runtime

@facchinm
Copy link
Member

Hi @pratikpc ,
the explicit fix looks perfect, while I would avoid adding the constexpr keyword; not because it's wrong in any way, just because the compiler should be smart enough to understand it, and it would make the signature different in classes where bool() is not constant (eg. the CDC Serial).
What do you think about it?

@pratikpc
Copy link
Contributor Author

pratikpc commented Sep 17, 2019

I'd say making it fixed rather than surviving on the whims of the compiler, especially in a language like C++ is a decent idea.
But am okay with dropping it.
The explicit part is of more importance given the safety benefits.
@facchinm done!

@facchinm facchinm merged commit b367b67 into arduino:master Sep 17, 2019
@facchinm
Copy link
Member

Merged, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants