How to disallow temporaries

后端 未结 10 1716
一个人的身影
一个人的身影 2020-12-02 05:19

For a class Foo, is there a way to disallow constructing it without giving it a name?

For example:

Foo(\"hi\");

And only allow it i

10条回答
  •  日久生厌
    2020-12-02 05:45

    Since the primary goal is to prevent bugs, consider this:

    struct Foo
    {
      Foo( const char* ) { /* ... */ }
    };
    
    enum { Foo };
    
    int main()
    {
      struct Foo foo( "hi" ); // OK
      struct Foo( "hi" ); // fail
      Foo foo( "hi" ); // fail
      Foo( "hi" ); // fail
    }
    

    That way you can't forget to name the variable and you can't forget to write struct. Verbose, but safe.

提交回复
热议问题