Why compiler provides default copy constructor

后端 未结 10 1946
别那么骄傲
别那么骄傲 2020-12-16 17:08

I wanted to know Why compiler provides default copy constructor..Whats the strategy behind that idea.

Thanks in Advance.

10条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 18:05

    A few points:

    It's important to be able to control if an object can or cannot be copied.

    If you don't want that an object can be copied, then you can declare the copy constructor private (and in C++ 0x you'll be able to say =delete). This is unchanged with your proposal however, the problem is simply reversed, ie. you could foresee a question like: "Why doesn't the compiler generate a default copy constructor when it knows what to do?"

    This will also be addressed in C++ 0x, as I believe there is an =default flag which will allow you to specify it:

    class C {
    public:
      C (C const &) = default;
    };
    

    It's beneficial to allow the compiler to implement the best possible version of the copy constructor.

    Ease of use aside, today the compiler is able to choose the most efficient technique for copying the object. For example, it might just use memcpy with the object if it knows that that is safe to do so.

    With your proposal, to achieve a similar optimzation today the compiler would need to analyze the constructor body to verify that it does nothing but shallow copy all the members. Not only is this non trivial, it can generally only happen when the constructor body is visible to all translation units.

    In C++ 0x =default gets round this.

    I wouldn't be surprised if, for C++ 0x, compilers and static analysis tools start generating warnings about "old style implicit default members".

提交回复
热议问题