vendredi 18 septembre 2020

c++ for frequently copy const field struct in a struct, should I use `shared_ptr`?

I have a Struct as a field of another Struct, and the field will be assigned to other object frequently. This field will not be changed once created, but it has a char array which I hope I can avoid copy. So should I set this field as a shared_ptr as below snippet demo to improve efficiency and avoid copy of the char array each time?

#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;
}

Anther question is there is no way I can initialize char c[6] field in Struct1 if I put it like this?

struct Struct1 {
    const int a;
    const string b;
    const char c[6]; // <-- here changed to const
};

Aucun commentaire:

Enregistrer un commentaire