Anand Shah
Anand Shah

Reputation: 143

STL container of structure having character array elements

Lets say I have structure that looks like below -

struct Member
{
    Membe(char* member1In, char* member2In)
    {
       strcpy(member1, member1In);
       strcpy(member2, member2In);
    }
    char member1[10];
    char member2[10];
};

and std::vector declared as

std::vector<Member> members{};

And I insert values using emplace_back() like below

members.emplace_back(value1, value2);

So my question is when array grows beyond capacity, it has to move to some other location. Who will allocate memory for Member structure ? Do I have to write my own copy, assignment and move operations or compiler provided are enough ? Will default provided operation do shallow copy and create problem ?

Upvotes: 2

Views: 72

Answers (2)

eerorika
eerorika

Reputation: 238311

Who will allocate memory for Member structure ?

std::vector will allocate the memory using the allocator that you provided (implicitly, by using the default argument).

Do I have to write my own copy, assignment and move operations or compiler provided are enough ?

The compiler provided ones are enough.

Will default provided operation do shallow copy

Yes, although it depends on what one means by shallow copy. The distinction between shallow and deep copy is only meaningful to referential types.

and create problem ?

No. Your class contains no pointers / references / iterators, so there is nothing that could be copied deeply, and no problem.

Upvotes: 5

john
john

Reputation: 87959

The vector will allocate the necessary memory.

For some classes you would need to write a copy constructor etc. But that would be true even if you weren't using the class in a vector.

For your class however the default copy constructor will work correctly. The simple rule of thumb is that if your class needs a destructor, then it also needs a copy constructor and an assignment operator. This is called the rule of three.

Upvotes: 2

Related Questions