简体   繁体   English

关于复制构造函数和NRVO

[英]Regarding copy constructor and NRVO

class Date
{
private:
int day,month,year;
public:
Date (int d,int m,int y)
{
day=d;
month=m;
year=y;
}
Date (Date &d)
{ 
day=d.day;
month=d.month;
year=d.year;
}
int monthDays(int month,int year)
{
    if((year%4)==0){
    if(month==4 || month==6 || month==9 || month==11){
        return 30;
    }
    else
    if(month==2){
        return 29;
    }
    else
        return 31;
    }
    else{
        if(month==4 || month==6 || month==9 || month==11){
            return 30;
        }
        else
        if(month==2){
            return 28;
        }
        else
        return 31;
    }
}
Date operator+ (const int k) 
{
    Date copy(day,month,year);
    int inc_days=k;
  if(inc_days<=(monthDays(copy.month,copy.year)-copy.day)){
        copy.day+=inc_days;
        return copy;
    }
    else{
        inc_days-=(monthDays(copy.month,copy.year)-copy.day);
        copy.day=monthDays(copy.month,copy.year);
        while(inc_days>0){
            copy.year+=(copy.month/12);
            copy.month+=1-12*(copy.month/12);
            if(inc_days>monthDays(copy.month,copy.year)){
                copy.day=monthDays(copy.month,copy.year);
                inc_days-=monthDays(copy.month,copy.year);
            }
            else{
                copy.day=inc_days;
                inc_days=0;
            }
        }
        return copy;
    }     
}
};
int main()
{
Date d1(2,3,2004); //uses another constructor //line 1
Date d3(d1); //line 2
Date d2=d1+2; //uses overloaded + operator //line 3
}

Even though line 2 does not take a temporary object as an argument I am still getting a compiler error if I don't add a const in the copy constructor argument. 即使第2行没有将临时对象作为参数,但是如果我没有在复制构造函数参数中添加const,我仍然会遇到编译器错误。 In case of line 3 , the overloaded operator returns an object using NRVO .So it should not use the copy constructor. 在第3行的情况下,重载的运算符使用NRVO返回一个对象,因此不应使用复制构造函数。 But it still gives a compiler error. 但是它仍然会给出编译器错误。 Both these errors vanish if I add a const in the copy constructor argument.But why should it give an error? 如果我在复制构造函数参数中添加一个const,这两个错误都会消失,但是为什么要给出错误呢?

Even if the copy constructor is optimized out by the compiler, the code must still compile correctly as if the copy constructor were theoretically called. 即使复制构造函数已由编译器优化,代码仍必须正确编译,就像从理论上调用了复制构造函数一样。 You need to make the parameter to the copy constructor a const reference in order to take a temporary object. 您需要使复制构造函数的参数成为const引用,以获取临时对象。

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

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