const-correctness和安全bool成语

fre*_*low 9 c++ const member-function-pointers const-correctness safe-bool-idiom

我有另外一个与安全bool成语有关的问题:

typedef void (Testable::*bool_type)() const;             // const necessary?
void this_type_does_not_support_comparisons() const {}   // const necessary?

operator bool_type() const
{
    return ok_ ? &Testable::this_type_does_not_support_comparisons : 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么在bool_type(typedef的),并this_type_does_not_support_comparisonsconst?无论如何,没有人应该通过返回指针实际调用成员函数,对吧?这const有必要吗?会operator bool_type(成员函数)违反常量,正确性,否则?

Che*_*Alf 5

"安全bool成语"是"我想要一辆既是跑车又是拖拉机,也许是一艘船"的问题的技术答案.实际答案不是技术答案......

也就是说,它解决的问题只是给出一个可以转换为bool但不能转换为其他任何东西的结果(否则该类的实例可以作为实际参数传递,例如正式参数int,例如).数据指针可以转换为void*.函数指针不是,至少在C++标准中是正确的(Posix是其他东西,也是实践).

在给出来自安全bool操作符的指针的情况下,使用成员函数指针可防止意外调用该函数. const收缩了一点,但如果命运已经把别人做的愚蠢的错误最大数量的路径上,那个人可能仍然设法调用什么也不做的功能.而不是const 我想我会让它有一个私有类型的参数,其他代码不能提供这样的参数,然后它不再是一个愚蠢的成员函数类型.

可以这样:

#include <stdio.h>

class Foo
{
private:
    enum PrivateArg {};
    typedef void (*SafeBool)( PrivateArg );
    static void safeTrue( PrivateArg ) {}

    bool    state_;

public:
    Foo( bool state ): state_( state ) {}

    operator SafeBool () const
    { return (state_? &safeTrue : 0); }
};

int main()
{
    if( Foo( true ) ) { printf( "true\n" ); }
    if( Foo( false ) ) { printf( "false\n" ); } // No output.

    //int const x1 = Foo( false );        // No compilado!
    //void* const x2 = Foo( false );      // No compilado!
}
Run Code Online (Sandbox Code Playgroud)

当然,实际的答案是这样的:

#include <stdio.h>

class Foo
{
private:
    bool    isEmpty_;

public:
    Foo( bool asInitiallyEmpty )
        : isEmpty_( asInitiallyEmpty )
    {}

    bool isEmpty() const { return isEmpty_; }
};

int main()
{
    if( Foo( true ).isEmpty() ) { printf( "true\n" ); }
    if( Foo( false ).isEmpty() ) { printf( "false\n" ); } // No output.

    //bool const x0 = Foo( false );       // No compilado!
    //int const x1 = Foo( false );        // No compilado!
    //void* const x2 = Foo( false );      // No compilado!
}
Run Code Online (Sandbox Code Playgroud)

总结wrt.提出的问题:

  • 为什么bool_type(typedef)和this_type_does_not_support_comparisons是const?

有人不太明白他们编码的是什么.或者,也许他们打算限制打电话,一点点的能力.但是,那是非常徒劳的措施.

  • 无论如何,没有人应该通过返回指针实际调用成员函数,对吧?

对.

  • const是必要的吗?

没有.

  • 运算符bool_type(成员函数)是否会违反const-correctness?

没有.

干杯&hth.,