以下代码仅在复制构造函数可用时才有效。
当我添加打印语句(通过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
使用内置规范。
目标:i686-apple-darwin10
配置:/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
线程模型:posix
gcc 版本 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:错误:在此上下文中
t.cpp:10:错误:'N::N(const N&)' 是私有的
t.cpp:26:错误:在此上下文中
这是一些真实代码的简化版本。
在实际代码中,我有一个包含 std::auto_ptr 的类。这意味着采用 const 引用的复制构造函数无效(没有一些工作),并且我收到一个错误,表明复制构造函数因此不可用:
也改变班级:
class N
{
public:
N(int) {}
private:
std::auto_ptr<int> data;
};
那么错误是:
t.cpp:25: 错误: 没有匹配函数调用'N::N(N)'</p>