c ++ copy constructor signature:是否重要 [英] c++ copy constructor signature : does it matter
问题描述
我目前的实现使用了大量具有此语法的复制构造函数
My current implementation uses lots of copy constructors with this syntax
MyClass :: Myclass(Myclass * my_class)
是真的(functionnaly)不同于
Is it really (functionnaly) different from
MyClass :: MyClass const MyClass& my_class)
为什么?
解决方案不是真正的复制构造函数。然而,进行更改意味着相当多的重构。
I was adviced that first solution was not a true copy constructor. However, making the change implies quite a lot of refactoring.
感谢!!!
推荐答案
第一个不是一个复制构造函数,而是一个转换构造函数。它从 MyClass *
转换为 MyClass
。
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。复制类对象
12.8. Copying class objects
2)类X的非模板构造函数是复制构造函数,如果它的
第一个参数是类型X& const X& amp; volatile X&或const volatile
X&,并且没有其他参数或者所有其他
参数都有默认参数(8.3.6).113)[例:X :: X(const
X&)和X :: X(X&,int = 1)是复制构造函数。
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.
假设您有:
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
它们完全不同的用途。
这篇关于c ++ copy constructor signature:是否重要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!