I totally see what you're getting at and agree that it's a potential problem.
(Though the real source of the problem is that in C++ is that 0 casts just tine
to a pointer, instead of having a proper pointer type, like nullptr is in
C++11. I digress, that observation doesn't actually help us solve this problem
in practice.)
I'm very afraid of breaking existing code, and also I am still rather fond of
the "if (s)" idiom.
Might another way of dealing with this be to add
operator std::string() const { return this->string(); }
That would allow assignment of ustring to std::string to do the obvious thing.
Would that suffice, or can you think of other scenarios in which operator bool
is likely to be an ongoing problem?
-- lg
On Jan 25, 2015, at 6:24 PM, Thiago Ize <[email protected]> wrote:
> I'm wondering if the following ustring function:
>
> /// Cast to int, which is interpreted as testing whether it's not an
> /// empty string. This allows you to write "if (t)" with the same
> /// semantics as if it were a char*.
> operator int (void) const { return !empty(); }
>
> is a good idea? Reason being that this allows for what is probably
> unexpected behavior in the common use case of trying to assign a ustring to a
> std::string (note how this case could also happen from a simple typo if the
> "u" in ustring was accidentally omitted). For instance:
> ustring my_ustring("string A");
> string my_string("string B");
> my_string = my_ustring;
> printf(" my_string=\"%s\" and\n my_ustring=\"%s\"\n", my_string.c_str(),
> my_ustring.c_str());
>
> will print out:
> my_string="" and
> my_ustring="string A"
>
> which is most likely not the intended result. If we get rid of this
> function, then the compiler will point out our mistake:
> foo.cpp:13:14: error: no viable overloaded '='
> my_string = my_ustring;
>
> I realize getting rid of this function would break lots of preexisting code,
> but I think this might be worth it in order to prevent this type of problem.
> If it's too big of a change, then at least it might be worth adding a comment
> to this function indicating that it will cause this problem.
>
--
Larry Gritz
[email protected]
_______________________________________________
Oiio-dev mailing list
[email protected]
http://lists.openimageio.org/listinfo.cgi/oiio-dev-openimageio.org