c++ - 为什么在此代码中使用复制构造函数?

标签 c++ copy-constructor

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;
}

执行这段代码给出 o/p:

A::A(int), n_=10
A::A(int), n_=20

显然,复制构造函数从未被调用。

class A
{
 public:
  A(const int n_);
  A& operator=(const A& that_);
 private:
  A(const A& that_);
};

但是,如果我们将其设为私有(private),则会出现此编译错误:

Test.cpp: In function ‘int main()’:
Test.cpp:21: error: ‘A::A(const A&)’ is private
Test.cpp:38: error: within this context

为什么编译器在实际没有使用复制构造函数时会报错?
我正在使用 gcc 版本 4.1.2 20070925 (Red Hat 4.1.2-33)

最佳答案

Core defect 391解释问题。

基本上,当前的 C++ 标准要求在将临时类类型传递给 const 引用时使用复制构造函数。

此要求将在 C++0x 中删除。

需要复制构造函数背后的逻辑来自这个案例:

C f();
const C& r = f(); // a copy is generated for r to refer to

关于c++ - 为什么在此代码中使用复制构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/919701/

相关文章:

c++ - C++函数调用到RISC-V系统调用

c++ - 在 NCurses 中滚动但包裹垫

c++ - 没有指针数据成员的类 - 复制构造函数 == 赋值运算符?

C++复制构造函数的奇怪之处

c++ - 使用 -pedantic 编译时采用 std::reference_wrapper 的模糊构造函数

c++ - C++ header 中的循环依赖。怎么找?

c++ - 为什么构造函数默认不显式?

c++ - 使用CPPCHECK的Red Hat Enterprise Linux(RHEL)上的C++宏问题

c++ - 具有指针成员且没有重写复制构造函数的类

c++ - 析构函数和复制构造函数调用..(为什么在这些时候调用它)