Why does C++ not have a const constructor?

后端 未结 5 681
生来不讨喜
生来不讨喜 2020-11-29 06:23

(Edit: Heavy change because previous example was flawed, which may make some answers/comments seem odd)

This might be an overly contrived, but the following

5条回答
  •  难免孤独
    2020-11-29 06:58

    In my opinion, the fact of that the ctors haven't return-type specification is what fails here. Any other imaginable syntax like for example

    class A
    {
        const A& ctor(...);
    }
    

    would be, imho, very valuable. For example, imagine such a situation of calling a method with prototype

    void my_method(const my_own_string_class& z);
    

    If my_own_string_class holds a ctor from char*, the compiler could choose this ctor, but as this ctor is not allowed to return a const object, it need to allocate and copy... If const return type were allowed, one could do

    class my_own_string_class
    {
        char *_ptr;
        public:
        const my_own_string_class& ctor(char *txt)
        : _ptr(txt)
        { return *this;}
     }
    

    provided that this special construct be restricted to the creation of temporal instances. (And dtor's must be mutable ;) ).

提交回复
热议问题