copy ctor

Hello.When are copy c-tors called?

Thanks in advance!
it's called if you ever pass a class into a function as an argument, or return a function;

1
2
3
class MyClass { };
MyClass A; // Default ctor
MyClass B(A); // Copy ctor 


1
2
3
4
MyClass SomeFunc(MyClass C) // Copy Ctor called to create C
{
   return C
}


cout << SomeFunc(A); // Copy ctor called to store the return value of SomeFunc before the cout
you could declare it as private so you'll see where it is called (by looking at compilation errors).



> When are copy c-tors called?

Whenever an object is copy initialized - ie. a new object is created which is a copy of another object of the same type.


> or return (from) a function;

Almost all compilers would apply RVO and elide the copy.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>

struct A
{
    A() { std::cout << "\tA::default_constructor\n\n" ; }
    A( const A& ) { std::cout << "\tA::copy_constructor\n\n" ; }
};

void foo( A ) {}

A bar() { A temp ; return temp ; }

int main()
{
    std::cout << "default-initialize an A\n" ; A a1 ; // default constructor of A

    std::cout << "make a copy of A\n" ; A a2 = a1 ; // copy constructor of A ;
    std::cout << "pass A by value\n" ; foo(a1) ; // copy constructor of A ;
    std::cout << "return A by value\n" ; A a3 = bar() ; // default constructor of A (NRVO)

    struct B { A a ; } ;
    std::cout << "default-initialize a B\n" ; B b1 ; // default constructor of A
    std::cout << "make a copy of B\n" ; B b2 = b1 ; // copy constructor of A
}


Output:
default-initialize an A
        A::default_constructor

make a copy of A
        A::copy_constructor

pass A by value
        A::copy_constructor

return A by value
        A::default_constructor

default-initialize a B
        A::default_constructor

make a copy of B
        A::copy_constructor

wikipedia says it CAN be called upon return.Would you explain more about RVO?
I read it.the first example was complex
Topic archived. No new replies allowed.