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?
initialization
1
2
3Class T
T a=b;
T a(b);function argument passing
1
2void func(T t);
f(a)function argument return
1
2T 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 | class String |
solution 1)
1 | std::ostream& operator<<(std::ostream& stream, const String string) |
const String string (매우 안좋은 코드)
- 입력값으로 객체를 복사
- 복사된 객체가 없어지면서 소멸함수에 의해 m_Buffer가 삭제된다.
const String&
string
객체를 참조함으로서 불필요한 객체의 생성을 막는다.
Example 2)
1 | String string = "Cherno"; |
solution 2)
Reference
- 이것이 C++ 이다, 최호성
- cppreference - copy constructors
- TheChernoProject
Comments
shortname
for Disqus. Please set it in_config.yml
.