개요
- 복사가 생략가능한 경우에 컴파일러 단계에서 복사 생략
- C++17부터는 복사 생략을 보장
예제 1
- 코드
#include <iostream>
using namespace std;
class Test {
public:
Test(const int &i) { cout << "base constructor call" << endl; }
Test(const Test &t) { cout << "copy constructor call" << endl; }
};
int main() {
Test t1(1);
cout << "------" << endl;
Test t2 = t1;
cout << "------" << endl;
Test t3(Test(1));
return 0;
}
- 실행 결과
base constructor call
------
copy constructor call
------
base constructor call
예제 2
- 코드
#include <iostream>
using namespace std;
class Test {
public:
Test(const int &i) { cout << "base constructor call" << endl; }
Test(const Test &t) = delete;
};
int main() {
Test t1(1);
cout << "------" << endl;
Test t2(Test(1));
return 0;
}
- 실행 결과
- C++11
test.cpp: In function ‘int main()’:
test.cpp:14:24: error: use of deleted function ‘Test::Test(const Test&)’
14 | Test t2(Test(1));
| ^
test.cpp:8:17: note: declared here
8 | Test(const Test &t) = delete;
| ^~~~
- C++17
base constructor call
------
base constructor call