Programming

Copy Constructor & Swallow/Deep Copy

def

The copy constructor is called whenever an object is initialized (by direct-initialization or copy-initialization) from another object of the same type.

when object initialized?

  1. initialization

    1
    2
    3
    Class T
    T a=b;
    T a(b);
  2. function argument passing

    1
    2
    void func(T t);
    f(a)
  3. function argument return

    1
    2
    T func()
    return a

Implicitly-declared copy constructor(Swallow Copy)

If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class. This implicitly-declared copy constructor has the form

Example 1) Error code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
class String
{
private:
char* m_Buffer;
unsigned int m_Size;
public:
String(const char* string)
{
m_Size = strlen(string);
m_Buffer = new char[m_Size+1];
memcpy(m_Buffer, string, m_Size);
m_Buffer[m_Size] = NULL;
}
~String()
{
cout << "소멸자" << endl;
delete[] m_Buffer;
}
char* GetBuffer() const
{
return m_Buffer;
}
};

std::ostream& operator<<(std::ostream& stream, const String string) {
stream << string.GetBuffer();
return stream;
}

int main()
{
String string = "Cherno";
cout << string << endl;

return 0;
}

solution 1)

1
std::ostream& operator<<(std::ostream& stream, const String string)

const String string (매우 안좋은 코드)

  1. 입력값으로 객체를 복사
  2. 복사된 객체가 없어지면서 소멸함수에 의해 m_Buffer가 삭제된다.

const String& string
객체를 참조함으로서 불필요한 객체의 생성을 막는다.

Example 2)

1
2
3
4
5
String string = "Cherno";
String second = string;

cout << string << endl;
cout << string << endl;

solution 2)

Reference

  1. 이것이 C++ 이다, 최호성
  2. cppreference - copy constructors
  3. TheChernoProject
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×