即使提供了完全参数,显式复制构造函数也会被忽略 [英] explicit copy constructor ignored even if exact argument was provided

查看:334
本文介绍了即使提供了完全参数,显式复制构造函数也会被忽略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已提供复制构造函数。当使用它时,完全相同的类型被传递给参数。仍然似乎编译器(gcc / g ++ 4.8.2)忽略显式复制构造函数的存在。
代码生成编译错误。为什么?
错误是:

The copy constructor has been provided. While using it exactly same type is passed to argument. Still the it seems the compiler( gcc/g++ 4.8.2) ignores existence of explicit copy constructor. The code generates compilation error. Why? The error is:

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]
 }
 ^

我已经浏览过

为什么我不能调用'explicit a(string x)'?

显式复制构造函数
基于这些链接,我已经尝试了强制复制构造(为了避免优化,请参考我的注释代码)。

I have already gone through
Why I am not able to invoke 'explicit a (string x)'? and Explicit copy constructor. Based on the those links and i have tried the forcing copy construction (to avoid optimization,Refer to my commented code).

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


推荐答案

复制构造函数被隐式调用

The copy constructor is called implicitly on return.

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

This code would call the copy constructor twice:

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

A(a)表示一个显式拷贝,然后返回时有一个隐式拷贝。

The A(a) means an explicit copy, and then there is an implicit copy on return.

如果你不允许隐式拷贝,那么你不能通过拷贝返回。您必须通过引用或指针(可能带有'd副本)返回。

If you want to disallow implicit copying, then you can't return by copy. You'll have to return by reference or pointer (probably with a new'd copy).

这篇关于即使提供了完全参数,显式复制构造函数也会被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆