【发布时间】:2010-12-22 01:36:11
【问题描述】:
以下代码仅在复制构造函数可用时才有效。
当我添加打印语句(通过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-苹果-darwin10
线程模型:posix
gcc 版本 4.2.1(Apple Inc. build 5646)[Alpha:~/X] myork%g++ t.cpp
t.cpp:在函数“int main()”中:
t.cpp:10:错误:'N::N(const N&)' 是私有的
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)’
【问题讨论】:
-
哪个编译器?这在 VC9 上编译得很好
-
@Captain:不是这样。两者都是有效的。我更喜欢上面使用的表格。
-
N const&完全有效。甚至有更好的理由。 -
添加到 Naveen 的评论 - VC6、Digital Mars 和 Comeau 对您的示例也没有任何问题。只有 GCC 3.4.5(我没有安装较新的)抱怨复制 ctor。我不明白为什么应该这样做。
-
这听起来和我最近遇到的一个问题非常相似:stackoverflow.com/questions/1615660/…
标签: c++ copy-constructor