You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++拷贝与移动语义疑问:程序触发trace trap异常原因解析

问题

我编写了如下代码模拟vector的行为,通过打印语句观察函数调用情况:

class Item {
    public:
        
        Item() {
            cout << "constructor" << endl;
        }

        Item(const Item& a) {
            cout << "copy constructor" << endl;
        }

        Item& operator=(const Item& a) {
            cout << "copy assignment" << endl;
        }

        Item(Item && a) {
            cout << "move constructor" << endl;
        }

        Item& operator=(Item && a) {
            cout << "move assignment" << endl;
        }

        ~Item() {
            cout << "destructor" << endl;
        }
};

接着定义了A类,希望构造A时不发生值拷贝:

class A {
public:
    Item x;

    A(Item & a) {
        x = std::move(a);
    }
};

调用代码如下:

Item a;
A q{a};

运行后输出:

constructor
constructor
move assignment
[1]    17802 trace trap  ./main

请问为何程序会触发trace trap异常?


原因分析

  • 你的Item类的赋值运算符(包括拷贝赋值和移动赋值)未返回*this,这违反了C++的语法规范。赋值运算符必须返回自身的引用,否则编译器无法获得预期的返回值,进而引发未定义行为,最终触发trace trap异常。
  • 执行x = std::move(a);时,移动赋值运算符执行完毕后没有返回值,但编译器期望它返回Item&类型的结果,这种不匹配会导致程序运行时出现非法内存访问,直接引发崩溃。

修复方案

给两个赋值运算符添加返回*this的语句即可:

Item& operator=(const Item& a) {
    cout << "copy assignment" << endl;
    return *this; // 添加返回语句
}

Item& operator=(Item && a) {
    cout << "move assignment" << endl;
    return *this; // 添加返回语句
}

内容的提问来源于stack exchange,提问作者morpheus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 11:54:54