1

I had the following class:

class A  
{  
public:  
    A(int i)  
        :m_n{i}  
    {
        std::cout << "A(int)\n";
    }
    // I don't need copy constructor.
    A(const A&) = delete;

private:
    int m_n;
};

Then I declared an array of A:

int main()
{
    A aa[] {1, 2, 3};

    return 0;
}

When I tried to compile the program on OnlineGDB
(https://www.onlinegdb.com/online_c++_compiler) using C++14, I got the following error:

main.cpp: In function 'int main()':  
main.cpp:38:20: error: use of deleted function 'A::A(const A&)'  
     A aa[] {1, 2, 3};  
                    ^  
main.cpp:22:5: note: declared here
     A(const A&) = delete;
     ^
main.cpp:16:5: note:   after user-defined conversion: A::A(int)
     A(int i)
     ^

Then I add copy constructor to class A:

A(const A& a)
    :m_n{a.m_n}
{
    std::cout << "A(const A&)\n"
}

and the program compiled and output the following:

A::A(int)
A::A(int)

My question:
since the copy constructor was never called, why shall I define it?

  • 3
    It's part of an optimization called [*copy elision*](https://en.wikipedia.org/wiki/Copy_elision) where copy-construction is *elided* (the copy constructor is not called). ***But*** the copy constructor still needs to exist for it to be possible, since not all copying can be elided (optimized away). – Some programmer dude Apr 18 '18 at 06:56
  • 1
    In C++17 it is unnecessary though, the elision is guaranteed. – miradulo Apr 18 '18 at 06:59
  • https://stackoverflow.com/questions/29759441/is-a-class-with-deleted-copy-constructor-trivially-copyable This might help you – yash wanth Apr 18 '18 at 07:16

0 Answers0