简体   繁体   English

为什么复制构造函数参数为const?

[英]Why is the copy-constructor argument const?

 Vector(const Vector& other) // Copy constructor 
 {
    x = other.x;
    y = other.y;

Why is the argument a const? 为什么参数是常量?

You've gotten answers that mention ensuring that the ctor can't change what's being copied -- and they're right, putting the const there does have that effect. 您已经得到答案,其中提到要确保ctor不能更改要复制的内容-而且它们是正确的,将const放在其中确实具有这种效果。

More important, however, is that a temporary object cannot bind to a non-const reference. 但是,更重要的是临时对象不能绑定到非常量引用。 The copy ctor must take a reference to a const object to be able to make copies of temporary objects. 复制ctor必须引用一个const对象,以便能够复制临时对象。

Because you are not going to modify the argument other inside the copy ctor as it is const. 因为您不会在复制ctor中修改other参数,因为它是const。

When you did x = other.x it essentially means this->x = other.x . 当您执行x = other.x它实际上意味着this->x = other.x So you are modifying only this object just by copying the values from other variable. 因此,仅通过复制other变量的值即可修改this对象。 Since the other variable is read-only here, it is passed as a const-ref. 由于other变量在这里是只读的,因此它将作为const-ref传递。

The traditional copy-ctor and friends take a const& parameter for reasons specified above. 出于上述原因,传统的copy-ctor和friends使用const&参数。 However, you should also look up move-semantics and r-value references (to be part of C++0x, if all goes well) to see why and when you will use copy-ctors without a const& parameter. 但是,您还应该查找移动语义r值引用 (如果一切顺利,将成为C ++ 0x的一部分),以了解为什么和何时使用不带const&参数的copy-ctors。 Another place to look at is the implementation of smart pointers such as auto_ptr (which have transfer of ownership semantics) where non-const parameters are useful. 另一个要看的地方是智能指针的实现,例如auto_ptr (具有所有权语义的转移),其中非const参数有用。

为了不能改变other (偶然)?

当我们尝试使用copy构造函数将一个对象复制到另一个对象时,我们需要维护原始对象(我们正在复制)的原始副本,因此在传递对象时,我们使其保持不变,并将其作为按引用传递。

The idea of a copy constructor is that you are copying the contents of the other object into the this object. 复制构造函数的想法是,您要将other对象的内容复制到this对象中。 The const is there to ensure that you don't modify the other object. const可以确保您不修改other对象。

Its not specific to copy constructor. 它不特定于复制构造函数。 In any function if you are not going to modify the internal state of the object then object will be passed as const . 在任何函数中,如果您不打算修改对象的内部状态,则对象将作为const传递。

Vector(const Vector& other) 
{
     //Since other is const, only public data member and public methods which are `const` can be accessed.
}

It can also come handy if you want to copy an object you only have a const reference to for example 如果您要复制一个对象,例如仅具有const引用,它也可以派上用场

...
const Vector& getPosition();
...

Vector* v = new Vector(getPosition());

If it wasn't for Vector(const Vector& other) that example would create a syntax error. 如果不是Vector(const Vector& other) ,则该示例将产生语法错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM