c ++复制构造函数签名:有关系吗 [英] c++ copy constructor signature : does it matter

查看:28
本文介绍了c ++复制构造函数签名:有关系吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我当前的实现使用大量具有这种语法的复制构造函数

MyClass::Myclass(Myclass* my_class)

它真的(功能上)不同于

MyClass::MyClass(const MyClass& my_class)

为什么?

有人建议我第一个解决方案不是真正的复制构造函数.然而,做出改变意味着相当多的重构.

谢谢!!!

解决方案

区别在于第一个不是拷贝构造函数,而是转换构造函数.它从 MyClass* 转换为 MyClass.

根据定义,复制构造函数具有以下签名之一:

MyClass(MyClass& my_class)MyClass(const MyClass& my_class)//....//cv 限定符和其他具有默认值的参数的组合

12.8.复制类对象

<块引用>

2) 类 X 的非模板构造函数是一个复制构造函数,如果它第一个参数的类型是 X&、const X&、volatile X&或 const 易失性X&,或者没有其他参数,或者所有其他参数具有默认参数 (8.3.6).113) [ 示例:X::X(constX&) 和 X::X(X&,int=1) 是复制构造函数.

您似乎混淆了两者.

假设你有:

结构 A{一个();A(A* 其他);A(常量A&其他);};一个;//使用默认构造函数乙(一);//使用复制构造函数A c(&a);//使用转换构造函数

它们一起服务于不同的目的.

My current implementation uses lots of copy constructors with this syntax

MyClass::Myclass(Myclass* my_class)

Is it really (functionnaly) different from

MyClass::MyClass(const MyClass& my_class)

and why?

I was adviced that first solution was not a true copy constructor. However, making the change implies quite a lot of refactoring.

Thanks!!!

解决方案

It's different in the sense that the first isn't a copy constructor, but a conversion constructor. It converts from a MyClass* to a MyClass.

By definition, a copy-constructor has one of the following signatures:

MyClass(MyClass& my_class)
MyClass(const MyClass& my_class)
//....
//combination of cv-qualifiers and other arguments that have default values

12.8. Copying class objects

2) A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).113) [ Example: X::X(const X&) and X::X(X&,int=1) are copy constructors.

EDIT: you seem to be confusing the two.

Say you have:

struct A
{
   A();
   A(A* other);
   A(const A& other);
};

A a;     //uses default constructor
A b(a);  //uses copy constructor
A c(&a); //uses conversion constructor

They serve different purposes alltogether.

这篇关于c ++复制构造函数签名:有关系吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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