初始化std :: array而不复制/移动元素 [英] initialize std::array without copying/moving elements

查看:125
本文介绍了初始化std :: array而不复制/移动元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
#include <string>
#include <array>

class C {
private:
    std::string a;
    std::string b;
    std::string c;
public:
    C(std::string a_, std::string b_, std::string c_) : a{a_},b{b_},c{c_} {}
    ~C(){};
    C(const C&) =delete;
    C(const C&&) =delete;
    const C& operator=(const C&) =delete;
    const C& operator=(const C&&) =delete;
};

std::array<C,2> array = {C("","",""),C("","","")};

int main()
{}

这不会编译(带有NDK和clang的Android Studio),并显示调用已删除的c的构造函数"错误.我知道我可以使用std::vectoremplace_back()直接在容器内部构造一个元素,但是在我的代码中,我只想使用固定大小的容器和不可复制/可移动的对象进行优化.我可能在这里缺少基本知识,但是有没有一种方法不必初始化std::array而不先构造单个元素然后将其复制到那里?

this won't compile (Android Studio with NDK and clang) with a "call to deleted constructor of c" error. I know that I can e.g. use a std::vector and emplace_back() to construct an element directly inside the container, but in my code I want to only use fixed-sized containers and non-copyable/moveable objects for optimization. I'm probably missing sth basic here, but isn't there a way to initialize the std::array without first having to construct the individual elements and then copy them there?

推荐答案

您可以使用括号括起来的初始化程序,而不是临时的c对象:

You can use brace enclosed initializers instead of temporary c objects:

std::array<c,2> array = {{{"",""},{"",""}}};

std::array<c,2> array{{{"",""},{"",""}}};

这篇关于初始化std :: array而不复制/移动元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆