c++ - 该值被复制而不是被 move 。为什么?

标签 c++ c++11 move

为什么这里声明的对象没有被 move ,而是被复制?它与复制省略有某种关系吗?当前代码不应该更改类的对象吗? 最初预计通过使用 std::move B 的内部结构会发生变化。我忽略了什么吗?有什么解决方法吗?

#include <iostream>
#include <algorithm>
#include <vector>

class A {
    public:
        A() {}
        auto&& get() { return v; }
        friend std::ostream& operator<<(std::ostream& o, A const& a) {
            o << "A: ";
            for (auto it = std::begin(a.v); it != std::end(a.v); ++it) { if (it != std::begin(a.v)) { o << " "; } o << *it; }
            return o;
        }
    private:
        std::vector<int> v;
};

class B {
    public:
        B() {};
        auto&& get() { return v; }
        friend std::ostream& operator<<(std::ostream& o, B const& b) {
            o << "B: { ";
            for (auto it = std::begin(b.v); it != std::end(b.v); ++it) { if (it != std::begin(b.v)) { o << " } { "; } o << *it; }
            return o << " }";
        }
    private:
        std::vector<A> v;
};

int main() {
    A a, a1, a2; B b;

    a.get().insert(a.get().end(), {1, 2, 3, 4});
    a1.get().insert(a1.get().end(), {5, 6, 7, 8});
    a2.get().insert(a2.get().end(), {9, 10, 11, 12});

    std::cout << a << "\n" << a1 <<  "\n" << a2;
    b.get().insert(b.get().end(), {a, a1, a2});
    std::cout << "\n" <<  b << "\n";

    a.get().push_back(std::move(b.get()[2].get()[2])); 

    std::cout << a << "\n" << a1 <<  "\n" << a2;
    std::cout << "\n" <<  b;
    return 0;
}

最佳答案

您在 int 上调用 std::move。对于非类类型,复制和 move 是相同的操作。

关于c++ - 该值被复制而不是被 move 。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50670416/

相关文章:

c++ - 如何在 STL 容器 C++11 中查找不同值

c++ - 模板方法和默认模板参数

c++ - 如何使用静态转换管理共享对象的生命周期?

javascript - HTML 下载 电影下载链接

java - 将文件 move 到其他位置

c++ - 指向成员模板类的指针

c++ - Ubuntu 机器上出现段错误,但 Mac 上却没有

linux - 'cd' 命令是否可以使用 'which' 命令?(我想将这两个命令合并为一个。)

c++ - C3861 : Identifier not found; method returning array c++

c++ - std::istream 类型是 EqualityComparable 吗?