c++ copy constructor signature : does it matter(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 ++复制构造函数签名:有关系吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:c ++复制构造函数签名:有关系吗
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
