对象作返回值时没有调用拷贝函数


#include
using namespace std;
class Point {
public:
    Point(int a, int b);
    Point(const Point& p);
    void print()
    {
        cout << x << " " << y << endl;
    }
private:
    int x, y;
};
Point::Point(int a, int b)
{
    x = a;
    y = b;
    cout << "Using normal constructor." << endl;
}
Point::Point(const Point& p)
{
    x = 2 * p.x;
    y = 2 * p.y;
    cout << "Using copy constructor." << endl;
}
void fun1(Point p)
{
    p.print();
}
Point fun2()
{
    Point p4(10, 30);

    return p4;
}
int main()
{
    Point p1(30, 40);

    p1.print();

    Point p2(p1);

    p2.print();
    Point p3 = p1;
    p3.print();
    fun1(p1);

    p2 = fun2();
    p2.print();
    return 0;

}

img


书上的例子我完全照抄,结果却不一样,这个最后一行结果是10 30,应该为20 60。
书上说对象作返回值时会调用拷贝函数赋值给一个临时对象,那应该会×2倍啊。而且应该会输出Using copy constructor.但实际情况并没有,我想知道这是为什么!
感谢回答!

VS2019 里运行如图:

img

这个应该和编译器优化有关,不同编译器结果不同

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 以下回答来自chatgpt:

    很有可能是因为你的代码中没有正确实现拷贝构造函数,导致返回的临时对象没有按照你期望的方式进行拷贝。你可以添加以下代码实现拷贝构造函数:

    class MyClass {
    public:
        int x, y;
    
        // 默认构造函数
        MyClass() {
            x = y = 0;
        }
    
        // 拷贝构造函数
        MyClass(const MyClass& other) {
            x = other.x;
            y = other.y;
            std::cout << "Using copy constructor" << std::endl;
        }
    
        // 重载乘法操作符
        MyClass operator*(int m) {
            MyClass temp;
            temp.x = x * m;
            temp.y = y * m;
            return temp;
        }
    };
    
    int main() {
        MyClass a;
        a.x = 10;
        a.y = 30;
    
        MyClass b = a * 2;
        std::cout << b.x << " " << b.y << std::endl;
        return 0;
    }
    

    上述代码中,我们添加了一个拷贝构造函数来确保在返回对象时正确拷贝对象。此外,我们还在类中重载了乘法操作符以实现我们所期望的对象乘以2的效果。输出应该为“Using copy constructor”。

    这样做能够解决你的问题,如果还有疑问或者代码无法正常运行,可以再发一条信息~


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^