How to disallow temporaries

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

    As is, with your implementation, you cannot do this, but you can use this rule to your advantage:

    Temporary objects cannot be bound to non-const references

    You can move the code from the class to an freestanding function which takes a non-const reference parameter. If you do so, You will get a compiler error if an temporary tries to bind to the non-const reference.

    Code Sample

    class Foo
    {
        public:
            Foo(const char* ){}
            friend void InitMethod(Foo& obj);
    };
    
    void InitMethod(Foo& obj){}
    
    int main()
    {
        Foo myVar("InitMe");
        InitMethod(myVar);    //Works
    
        InitMethod("InitMe"); //Does not work  
        return 0;
    }
    

    Output

    prog.cpp: In function ‘int main()’:
    prog.cpp:13: error: invalid initialization of non-const reference of type ‘Foo&’ from a temporary of type ‘const char*’
    prog.cpp:7: error: in passing argument 1 of ‘void InitMethod(Foo&)’
    

提交回复
热议问题