复制构造函数 VS 构造函数,并将类指针作为参数
copy constructor VS constructor with a class pointer as parameter
Q1:"self class typed pointer constructor"是否有一个体面/正式的名称?
Q2:为什么复制构造函数比"自类类型指针构造函数"更有名?
或者我们必须使用复制构造函数而不是"自类类型指针构造函数"的情况是什么?
class MyClass
{
public:
int i;
MyClass()
{
i = 20;
}
//Copy constructor
MyClass(MyClass const & arg)
{
i = arg.i;
}
//What kind of Constructor is this one?
MyClass(MyClass* pArg)
{
i = pArg->i;
}
};
int main() {
MyClass obj;
MyClass* p = new MyClass();
//call copy constructor
MyClass newObj(obj); //call copy constructor directly
MyClass newObj2(*p); //dereference pointer and then call copy constructor
MyClass* pNew = new MyClass(*p); //dereference pointer and then call copy constructor
//Call THE constructor
MyClass theObj(&obj); //get the address, call THE constructor
MyClass theObj2(p); //call pointer constructor directly
MyClass* ptheNew = new MyClass(p); //call pointer constructor directly
}
它没有特别的名字,因为它没有什么特别的。
复制构造函数"更出名",因为它很特别。 它很特别,因为它是语言工作方式的基本组成部分。 如果不声明复制构造函数,则在大多数类中,将为您隐式定义一个。 它涉及许多基本操作,例如:
void foo(MyClass obj) // the copy ctor is (potentially) called to create this parameter
{
...
}
MyClass bar() // the copy ctor is (potentially) called when this function returns, and when it result is used
{
...
}
MyClass a;
MyClass b(a); // This calls the copy constructor
MyClass c = b; // So does this
请注意,在许多情况下,副本被优化掉了。请参阅复制 Elision。 此外,在 C++11 中,移动构造函数在以前调用复制构造函数的许多地方被调用。 但是移动构造函数也可以在可能发生复制省略的相同位置进行优化。
我想不出你使用"THE constructor"的很多原因,正如你所说的那样。
附带说明一下,复制构造函数几乎总是应该具有以下签名:
MyClass(MyClass const &)
不是这个:
MyClass(MyClass &)
对于C++中的对象,我们通常使用引用而不是指针。我们可以使用引用来获取对象的地址,并且比您可以使用 '." 来访问它的方法或数据,它比 '->' 更简单、更直接。我认为没有必要使用"THE 构造函数"。
相关文章:
- 如果基类包含双指针成员,则派生类的构造函数
- 复制构造函数C++无法正确复制指针
- 使用基类指针调用基类的值构造函数的语法是什么?
- C++ 对象指针数组的复制构造函数
- 构造函数 (C++) 中的 char 指针参数存在问题
- 为什么使用 std::istream_iterator 构造函数返回指针
- 在对象构造期间,将指向尚未构造的子对象的指针传递给另一个子对象的构造函数是否危险?
- 使用指向成员函数的指针在另一个类中调用类构造函数
- 通过从构造函数中的'this'复制的指针改变常量对象
- 为什么指针对象没有调用默认构造函数
- 函数返回时,带指针的复制构造函数失败
- 如何编写复制构造函数来复制指针?
- 如何使用函数(而不是构造函数)将派生类对象分配给基类指针
- 使用 Rcpp 公开将指向对象的指针作为参数的构造函数
- std::shared_ptr 使用别名构造函数,是否可以检索初始指针值?
- 如何正确实现具有原始指针的类的复制构造函数?
- 构造函数主体内的本地指针C++内存泄漏
- 如何在将原始指针移动到基类构造函数之前从unique_ptr中提取原始指针
- 有没有办法通过读取 c++ 中的文件来构造函数指针
- 构造函数指针改变