다음 코드는 복사 생성자가 사용 가능한 경우에만 작동합니다.복사 생성자 임시 개체와 함께 필요
프린트 문을 (std::cout
을 통해) 추가하고 사용 가능한 복사 생성자를 만들 때 (필자는 불필요한 복사본을 제거하는 컴파일러 트릭이 있다고 가정합니다).
아래의 출력 operator <<
과 아래의 함수 plop()
(여기서 임시 개체를 만들 때)은 복사 생성자가 필요하지 않습니다. 누군가 const 참조 (또는 내가 잘못하고있는 일)로 모든 것을 전달할 때 언어가 필요로하는 이유를 설명 할 수 있습니까?
#include <iostream>
class N
{
public:
N(int) {}
private:
N(N const&);
};
std::ostream& operator<<(std::ostream& str,N const& data)
{
return str << "N\n";
}
void plop(std::ostream& str,N const& data)
{
str << "N\n";
}
int main()
{
std::cout << N(1); // Needs copy constructor (line 25)
plop(std::cout,N(1)); // Needs copy constructor
N a(5);
std::cout << a;
plop(std::cout,a);
}
컴파일러 :
[Alpha:~/X] myork% g++ -v
Using built-in specs.
Target: i686-apple-darwin10
Configured with: /var/tmp/gcc/gcc-5646~6/src/configure --disable-checking --enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.2/ --with-slibdir=/usr/lib --build=i686-apple-darwin10 --with-gxx-include-dir=/include/c++/4.2.1 --program-prefix=i686-apple-darwin10- --host=x86_64-apple-darwin10 --target=i686-apple-darwin10
Thread model: posix
gcc version 4.2.1 (Apple Inc. build 5646)[Alpha:~/X] myork% g++ t.cpp
t.cpp: In function ‘int main()’:
t.cpp:10: error: ‘N::N(const N&)’ is private
t.cpp:25: error: within this context
t.cpp:10: error: ‘N::N(const N&)’ is private
t.cpp:26: error: within this context
이 진짜 코드의 단순화 된 버전입니다.
실제 코드에는 std :: auto_ptr이 포함 된 클래스가 있습니다. 클래스도
변경 :
class N
{
public:
N(int) {}
private:
std::auto_ptr<int> data;
};
이것은 const를 참조 소요 복사 생성자는 (몇 가지 작업없이) 유효하지 않습니다 내가 복사 생성자가 그것 때문에 사용할 수 없음을 나타내는 오류가 발생하고 있음을 의미
오류는 다음과 같습니다
t.cpp:25: error: no matching function for call to ‘N::N(N)’
컴파일러는 무엇입니까? 이것은 VC9에서 잘 컴파일됩니다. – Naveen
N (N const &)은 N (const N &)이어야합니다. –
@Captain : 실제로는 아닙니다. 둘 다 유효합니다. 나는 위에서 사용하는 형식을 선호합니다. –