其他分享
首页 > 其他分享> > c-即使提供了精确参数,也将忽略显式副本构造函数

c-即使提供了精确参数,也将忽略显式副本构造函数

作者:互联网

提供了副本构造函数.使用它时,会将完全相同的类型传递给参数.仍然似乎编译器(gcc / g 4.8.2)忽略了显式副本构造函数的存在.
该代码生成编译错误.为什么?
错误是:

t.cpp: In function ‘A f(const A&)’:
t.cpp:19:12: error: no matching function for call to ‘A::A(const A&)’
     return a;  //compilation error with gcc 4.8.2
            ^
t.cpp:19:12: note: candidate is:
t.cpp:14:5: note: A::A()
     A(){}
     ^
t.cpp:14:5: note:   candidate expects 0 arguments, 1 provided
t.cpp:21:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

我已经经历了
Why I am not able to invoke ‘explicit a (string x)’?

Explicit copy constructor.
基于这些链接,我尝试了强制复制构造(为避免优化,请参阅我的注释代码).

#include <iostream>
using namespace std;

class A 
{
public:
    explicit A(const A& a)   // an explicit copy constructor
    //A(const A&)   // an copy constructor, pretty much default one. 
                    //using it solves any compile problem.
    {
        cout << "\nin the copy constructor" << endl;
    }

    A(){}
};
//////////////////////////////////
A f(const A &a)
{   
    return a;  //compilation error with gcc 4.8.2
    //return A(a);   // even tried this to avoid optimization. does not work 
}
///////////////////////////////////
int main()
{
    //A a;
    //f(a);  
    return 0;
}

解决方法:

复制构造函数在返回时(以及在按值传递参数时)隐式调用.

此代码将调用复制构造函数两次:

A f(const A &a)
{   
    return A(a);
}

A(a)表示显式副本,然后在返回时存在隐式副本.

如果要禁止隐式复制,则也不能按副本返回.您必须按引用或指针(可能带有新副本)返回.

在C 11及更高版本中,我相信上面的代码将改为调用move构造函数(如果已定义)作为返回值(尽管它仍将为显式调用调用copy构造函数),并且这样应该更有效.

标签:explicit,c,copy-constructor
来源: https://codeday.me/bug/20191013/1907448.html