gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 15:38:24 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com