如何在元组向量中构造不可复制的对象? [重复]

问题描述 投票:0回答:1

我有一个不可复制的类

A
,我想将其移动到元组向量中(请参见下面的代码)。我明白为什么下面的代码不起作用,但我想知道是否有一种聪明的方法可以在不改变我的类的实现的情况下让它工作。任何帮助是极大的赞赏。谢谢:)

#include <iostream>
#include <vector>
#include <tuple>

class A {
    public:
    int val1;
    int val2;

    A(int v1, int v2): val1(v1), val2(v2) {}

    // make non-copyable
    A(const A &other) = delete;
    A &operator=(const A &other) = delete;
};

int main() {
    std::vector<std::tuple<int, int, A>> my_as;

    my_as.emplace_back(4, 3, A(4, 2)); // Error, how to fix this?

    return 0;
}

c++ vector stl tuples move
1个回答
0
投票

解决这个问题的一种可能方法是使用像这样的唯一指针。


#include <iostream>
#include <vector>
#include <tuple>
#include <memory>

class A {
    public:
    int val1;
    int val2;

    A(int v1, int v2): val1(v1), val2(v2) {}

    // make non-copyable
    A(const A &other) = delete;
    A &operator=(const A &other) = delete;
};

int main() {
    std::vector<std::tuple<int, int, std::unique_ptr<A>>> my_as;

    my_as.emplace_back(4, 3, std::make_unique<A>(4, 2));
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.