C++11 c++;对于结构中的频繁复制常量字段结构,我应该使用“shared_ptr”吗?
我有一个C++11 c++;对于结构中的频繁复制常量字段结构,我应该使用“shared_ptr”吗?,c++11,constants,shared-ptr,C++11,Constants,Shared Ptr,我有一个Struct作为另一个Struct的字段,该字段将经常分配给其他对象。该字段创建后不会更改,但它有一个字符数组,我希望可以避免复制。那么,我是否应该将此字段设置为共享的\u ptr,如下代码片段演示,以提高效率并避免每次复制字符数组 #include <string> #include <iostream> #include <cstring> #include <memory> using namespace std; struct
Struct
作为另一个Struct
的字段,该字段将经常分配给其他对象。该字段创建后不会更改,但它有一个字符数组,我希望可以避免复制。那么,我是否应该将此字段设置为共享的\u ptr
,如下代码片段演示,以提高效率并避免每次复制字符数组
#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;
}
将
Struct1
存储为成员。使用探查器查看热点的位置。
struct Struct1 {
const int a;
const string b;
const char c[6]; // <-- here changed to const
};