为什么在这段代码中使用copy ctor? [英] Why is the copy ctor used in this code?
问题描述
class A
{
public:
A(const int n_);
A(const A& that_);
A& operator =(const A& that_);
};
A :: A(const int n_)
{cout< A :: A(int),n_ =<< n - << endl }
A :: A(const A& that_)//这是第21行
{cout< A :: A(const A&)<< endl }
A& A :: operator =(const A& that_)
{cout< A :: operator =(const A&)<< endl }
int foo(const A& a_)
{return 20; }
int main()
{
A a(foo(A(10))); //这是第38行
return 0;
}
执行此代码会产生o / p:
A :: A(int),n_ = 10
A :: A(int),n_ = 20
p>
显然,从不调用复制构造函数。
class A
{
public:
A(const int n_);
A& operator =(const A& that_);
private:
A(const A& that_);
};但是,如果我们将它设置为私有,则会发生编译错误:
Test.cpp:在函数'int main()':
Test.cpp:21:error:'A :: A A&)'为private
Test.cpp:38:错误:在此上下文中
编译器会在实际上没有使用拷贝构造函数时提出抱怨?
我使用的是gcc版本4.1.2 20070925(Red Hat 4.1.2-33)
解决方案
基本上,当前的C ++标准需要一个复制构造函数,以便在将类类型的临时传递给const引用时可用。
此要求将在C ++ 0x中删除。
需要复制构造函数的逻辑来自这种情况: / p>
C f();
const C& r = f(); //为r生成一个副本以引用
class A
{
public:
A(const int n_);
A(const A& that_);
A& operator=(const A& that_);
};
A::A(const int n_)
{ cout << "A::A(int), n_=" << n_ << endl; }
A::A(const A& that_) // This is line 21
{ cout << "A::A(const A&)" << endl; }
A& A::operator=(const A& that_)
{ cout << "A::operator=(const A&)" << endl; }
int foo(const A& a_)
{ return 20; }
int main()
{
A a(foo(A(10))); // This is line 38
return 0;
}
Executing this code gives o/p:
A::A(int), n_=10
A::A(int), n_=20
Apparently the copy constructor is never called.
class A
{
public:
A(const int n_);
A& operator=(const A& that_);
private:
A(const A& that_);
};
However, if we make it private, this compile error occurs:
Test.cpp: In function ‘int main()’:
Test.cpp:21: error: ‘A::A(const A&)’ is private
Test.cpp:38: error: within this context
Why does the compiler complain when it doesn't actually use the copy constructor?
I am using gcc version 4.1.2 20070925 (Red Hat 4.1.2-33)
解决方案 Core defect 391 explains the issue.
Basically, the current C++ standard requires a copy constructor to be available when passing a temporary of class type to a const reference.
This requirement will be removed in C++0x.
The logic behind requiring a copy constructor comes from this case:
C f();
const C& r = f(); // a copy is generated for r to refer to
这篇关于为什么在这段代码中使用copy ctor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!