为什么C ++复制构造函数必须使用const对象? [英] Why C++ copy constructor must use const object?

查看:193
本文介绍了为什么C ++复制构造函数必须使用const对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解,当我们定义类的时候,类的复制构造函数是必需的,因为三个规则状态。我还注意到复制构造函数的参数通常是 const ,如下面的代码所示:

I understand that when we define a class copy constructor of the class is necessary as Rule of three states. I also notice that the argument of the copy constructor is usually const as the following codes illustrate:

class ABC
{
   public:
       int a;
       int b;
       ABC(const ABC &other)
       { 
         a = other.a;
         b = other.b;
       }
}

我的问题是,如果复制构造函数不是const:

My question is what would happen if the argument of the copy constructor is not const:

  class ABC
    {
       public:
           int a;
           int b;
            ABC(ABC &other)
       { 
         a = other.a;
         b = other.b;
       }
    }

我理解在某些情况下,复制构造函数是const,那么第二个实现将失败。此外,如果复制构造函数的参数是const,那么要复制的对象在此过程中不会更改其内容。但是,我注意到有些人仍然使用第二个实现,而不是第一个。有什么理由第二个实施是首选吗?

I understand that in some cases if the argument of the copy constructor is const then the second implementation would fail. Also if the argument of the copy constructor is const then the object to be copied will not change its content during the process. However, I do notice that some people still use the second implementation rather than the first one. Are there any reasons that the second implementation is preferred?

推荐答案


  • 逻辑上,修改一个对象想要做一个副本,虽然有时它可能有一些意义,像一个情况,你想要存储的时间这个对象被复制的时间。但是这可以与存储此信息的 mutable 成员变量一起工作,并且甚至可以修改const对象(第二点将证明这种方法)

    • Logically, it should make no sense to modify an object of which you just want to make a copy, though sometimes it may have some sense, like a situation where you'd like to store the number of time this object has been copied. But this could work with a mutable member variable that stores this information, and can be modified even for a const object (and the second point will justify this approach)

      您希望能够创建const对象的副本。但是如果你不使用const限定符传递你的参数,那么你不能创建const对象的副本...

      You would like to be able to create copy of const objects. But if you're not passing your argument with a const qualifier, then you can't create copies of const objects...

      从临时引用复制,因为临时对象是rvalue,并且不能绑定到非const的引用。有关详细说明,我建议 Herb Sutter的文章

      You couldn't create copies from temporary reference, because temporary objects are rvalue, and can't be bound to reference to non-const. For a more detailed explanation, I suggest Herb Sutter's article on the matter

      这篇关于为什么C ++复制构造函数必须使用const对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆