How to disallow temporaries

后端 未结 10 1710
一个人的身影
一个人的身影 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:42

    Simply don't have a default constructor, and do require a reference to an instance in every constructor.

    #include 
    using namespace std;
    
    enum SelfRef { selfRef };
    
    struct S
    {
        S( SelfRef, S const & ) {}
    };
    
    int main()
    {
        S a( selfRef, a );
    }
    

提交回复
热议问题