How to disallow temporaries

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

    Declare one-parametric constructor as explicit and nobody will ever create an object of that class unintentionally.

    For example

    class Foo
    {
    public: 
      explicit Foo(const char*);
    };
    
    void fun(const Foo&);
    

    can only be used this way

    void g() {
      Foo a("text");
      fun(a);
    }
    

    but never this way (through a temporary on the stack)

    void g() {
      fun("text");
    }
    

    See also: Alexandrescu, C++ Coding Standards, Item 40.

提交回复
热议问题