问题描述
我有一个Struct
作为另一个Struct
的字段,并且该字段会经常分配给其他对象。创建后该字段将不会更改,但是它具有一个char数组,希望我可以避免复制。因此,是否应该像下面的代码片段演示一样将此字段设置为shared_ptr
,以提高效率并避免每次复制char数组?
#include <string>
#include <iostream>
#include <cstring>
#include <memory>
using namespace std;
struct Struct1 {
const int a;
const string b;
char c[6];
};
struct Struct3 {
const shared_ptr<Struct1> struct1;
const int d;
const string e;
};
int main() {
int a = 10;
auto b = "b";
char cc[6] = "67890";
auto struct1_ptr = shared_ptr<Struct1>(new Struct1{a,b});
strcpy(struct1_ptr->c,cc);
Struct3 struct3{struct1_ptr,10,"e"};
cout << struct3.struct1->c << endl;
}
另一个问题是,如果我这样说,是否无法初始化char c[6]
中的Struct1
字段?
struct Struct1 {
const int a;
const string b;
const char c[6]; // <-- here changed to const
};
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)