+ -
当前位置:首页 → 问答吧 → 这难道是编译器的bug?

这难道是编译器的bug?

时间:2011-12-27

来源:互联网

程序如下:
C/C++ code
#include <iostream>
using namespace std;
class Point
{
    public:
      Point(int=0,int=0);
      Point(const Point&);     
      void displayxy();
      ~Point();
    private:
      int X,Y;
};
Point::Point(int x,int y)     
{
    X=x;
    Y=y;
    cout<<"Constructor is called!";
    displayxy();
}
Point::Point(const Point& p)    
{
    X=p.X;
    Y=p.Y;
    cout<<"Copy constructor is called!";
    displayxy();
}
Point::~Point()
{
    cout<<"Destructor is called!";
    displayxy();
}
void Point::displayxy()
{
    cout<<"("<<X<<","<<Y<<")"<<endl;
}
Point func(Point p)
{
    int x=10*2;
    int y=10*2;
    Point pp(x,y);
    return pp;
}
int main()
{
    Point p1(3,4);
    Point p2=p1;
    p2=func(p1);
    return 0;

}


在codeblocks的运行结果:
Constructor is called!(3,4)
Copy constructor is called!(3,4)
Copy constructor is called!(3,4)
Constructor is called!(20,20)
Destructor is called!(20,20)
Destructor is called!(3,4)
Destructor is called!(20,20)
Destructor is called!(3,4)

Process returned 0 (0x0) execution time : 0.061 s
Press any key to continue.
在vc的运行结果:
Constructor is called!(3,4)
Copy constructor is called!(3,4)
Copy constructor is called!(3,4)
Constructor is called!(20,20)
Copy constructor is called!(20,20)
Destructor is called!(20,20)
Destructor is called!(3,4)
Destructor is called!(20,20)
Destructor is called!(20,20)
Destructor is called!(3,4)
Press any key to continue
为什么会这样呢?



作者: zoopang   发布时间: 2011-12-27

感觉vc的结果比较符合我的推论。p2=func(p1);
这块是明显需要调用拷贝构造函数的

作者: chenph_210   发布时间: 2011-12-27

对ISO/IEC 14882 2011实现程度不同造成的,新的C++规范引入了右值引用,通过适当的重载能减少对象无意义复制~

作者: mscf   发布时间: 2011-12-27

不同编译器实现不一样很正常,有些方面C++规范本来就没指定,实现有自己的灵活性~

作者: mscf   发布时间: 2011-12-27

看上去是code::blocks优化了一下,将你的p2=func(p1)优化为将p2的引用传递进来,所以少了return pp时产生的临时对象。
BUG倒谈不上,一般情况下因为这样的优化产生的问题较少。

作者: ww884203   发布时间: 2011-12-27

这不是BUG,楼主请自行查找命名返回值优化NRVO。

作者: supermegaboy   发布时间: 2011-12-27

我算服了csdn了,从7楼一直吃到14楼~~~

作者: Demon__Hunter   发布时间: 2011-12-27

引用 15 楼 demon__hunter 的回复:
我算服了csdn了,从7楼一直吃到14楼~~~

这个是csdn的bug?还是人为的?

作者: Demon__Hunter   发布时间: 2011-12-27

不同编译器在临时对象返回上实现可能不一样,标准在这方面没有规定吧。

作者: cattycat   发布时间: 2011-12-27

我晕,我的回复不见了
引用 18 楼 cattycat 的回复:
不同编译器在临时对象返回上实现可能不一样,标准在这方面没有规定吧。

++
code::blocks用的是gcc编译器,与VC对程序的实现是不同的

作者: keiy   发布时间: 2011-12-27