Why is the copy-constructor argument const?

前端 未结 8 2028
时光说笑
时光说笑 2020-11-29 00:30
 Vector(const Vector& other) // Copy constructor 
 {
    x = other.x;
    y = other.y;

Why is the argument a const?

相关标签:
8条回答
  • 2020-11-29 01:25

    The traditional copy-ctor and friends take a const& parameter for reasons specified above. 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. 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.

    0 讨论(0)
  • 2020-11-29 01:34

    It can also come handy if you want to copy an object you only have a const reference to for example

    ...
    const Vector& getPosition();
    ...
    
    Vector* v = new Vector(getPosition());
    

    If it wasn't for Vector(const Vector& other) that example would create a syntax error.

    0 讨论(0)
提交回复
热议问题