小编Rod*_*tes的帖子

为什么我不能使用引用变量实现移动构造函数?

移动构造函数通常的实现方式是这样的:

class Test {
public:
    int *ptr;
    Test() {
    }
    Test(Test&& t) {
        ptr = t.ptr;
        t.ptr = nullptr;
    }
};

int main() {
    Test t = Test(Test());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

购买为什么我们不能像这样实现它们:

class Test {
public:
    int *ptr;
    Test() {
    }
    Test(Test& t) {
        ptr = t.ptr;
        t.ptr = nullptr;
    }
};

int main() {
    Test t = Test(Test());
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

第二段代码似乎运行得很好。我不明白为什么我们不能那样做。

c++ constructor move

2
推荐指数
2
解决办法
163
查看次数

标签 统计

c++ ×1

constructor ×1

move ×1