c++ - 如何创建不可移动/复制构造的对象数组

标签 c++ arrays c++11 constructor

如果我创建一个像这样的对象数组,我会遇到麻烦:

SM sc[8]{{0},{1},{2},{3},{4},{5},{6},{7}};

SM 的构造函数定义为:

SM::SM(int);

因为在 c++ 中 Each member is copy-initialized from the corresponding initializer-clause. is given, I have a unsolved problem.

我已经读过:

Move Constructors and Static Arrays

Initialization of member array objects avoiding move constructor

Move constructor is required even if it is not used. Why?

constexpr array of constexpr objects using move ctor

是的,所有答案都很好地描述了列表初始化的内容,但我现在找不到如何获取静态对象数组的想法。

这个问题有解决办法吗?创建一个指针数组并使用 new 或 new@ 操作进行运行时初始化需要更多的运行时内存空间。这有点问题,因为我使用的是 AVR 8 位 Controller 。

最佳答案

只是一些反馈,在由于代码片段的答案中:

调整 3rd link 处的代码到:

#include <iostream>
using namespace std;

struct SM {
    int val;
    SM(int a) : val(a) { cout <<"Constructor val="<<a<<endl;}
    ~SM() { cout << "Destructor val="<<val<<endl; }

    SM(const SM& ) = delete;
    SM(SM&& ) = delete;
};

int main()
{
    SM sc[8] = { {0},{1},{2},{3},{4},{5},{6},{7} };
    return 0;
}

编译

g++ -std=c++11

并运行,结果是:

Constructor val=0
Constructor val=1
Constructor val=2
Constructor val=3
Constructor val=4
Constructor val=5
Constructor val=6
Constructor val=7
Destructor val=7
Destructor val=6
Destructor val=5
Destructor val=4
Destructor val=3
Destructor val=2
Destructor val=1
Destructor val=0

到底是什么问题?

关于c++ - 如何创建不可移动/复制构造的对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31791710/

相关文章:

c# - 如何在 C# 中编码(marshal) C++ 枚举

arrays - 在 ColdFusion 中使用 JSON 数据

arrays - 在 Swift 中通过 segue 传递后访问数组值的问题

C++11:如何检查类型是否是 "heterogeneous"非类型参数的给定类模板的实例化?

c++ - 编译器和 CPU 重新排序

c++ - 即时返回函数调用会编译为 "nop"指令吗?

c++ - 指向静态成员函数的指针是 "invalid"作为 g++ 的模板参数

c++ - QT 用比 SLOT 更少的参数连接 SIGNAL

c++ - 为什么 puts in my_strcpy 函数没有打印下面给定代码中的值?

c# - 将返回类型转换为数组 C#