explicit copy constructor ignored even if exact argument was provided

后端 未结 1 1393
南方客
南方客 2021-01-24 05:52

The copy constructor has been provided. While using it exactly same type is passed to argument. Still the it seems the compiler( gcc/g++ 4.8.2) ignores existence of explicit cop

相关标签:
1条回答
  • 2021-01-24 06:09

    The copy constructor is called implicitly on return (and also when passing an argument by value).

    This code would call the copy constructor twice:

    A f(const A &a)
    {   
        return A(a);
    }
    

    The A(a) means an explicit copy, and then there is an implicit copy on return.

    If you want to disallow implicit copying, then you can't return by copy, either. You'll have to return by reference or pointer (probably with a new'd copy).


    In C++11 and up, I believe that the code above would instead call the move constructor (if defined) for the return (though it would still call the copy constructor for the explicit call), and that should be more efficient.

    0 讨论(0)
提交回复
热议问题