Defining double exclamation?

前端 未结 7 1939
失恋的感觉
失恋的感觉 2021-02-04 06:43

I understand what a double exclamation mark does (or I think I understand) but I am not sure how it is defined on a random object. For example in the code snippet below:

7条回答
  •  野性不改
    2021-02-04 07:09

    The code is horribly complicated. In reality, you want to test whether the getAssigment method is successful and whether the assigned pointer is non-null.

    The code tests that, albeit in a convoluted fashion, taking advantage of weak typing, rather than trying to embrace explicitness and C++’ strong typing. As a consequence, it’s not idiomatic C++ and rather harder to understand than necessary.

    In particular, don’t use !!a in C++. This is an established idiom in weakly-typed languages such as JavaScript to coerce a value into a boolean type. But in C++, this is not commonly used.

    It’s not clear what the code does since hasSolution isn’t defined or used. However, I suspect that the code is supposed to be equivalent to the following:

    Assignment *a;
    return getAssignment(query, a) and a == nullptr;
    

    (Before C++11, you need to write 0 instead of nullptr.)

    However, this code still reveals a bad design: why is a passed by reference? Why isn’t it the return value? Worse, a is never used, so unnecessary. If a is indeed unnecessary, it should be left out completely. If it’s necessary, it should be the return value. In other words, the prototype of getAssignment should be as follows:

    Assignment* getAssignment(the_type_of_query query);
    

    And it should be used simply as follows:

    Assignment* a = getAssignment(query);
    

    Furthermore, I suspect that this code actually assigns memory ownership to the raw pointer a. This is strongly discouraged in modern C++. Either use no pointers or a smart pointer.

提交回复
热议问题