简体   繁体   English

STL 具有字符数组元素的结构容器

[英]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 声明为

std::vector<Member> members{};

And I insert values using emplace_back() like below我使用emplace_back()插入值,如下所示

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?谁来为 Member 结构分配 memory? 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?默认提供的操作会做浅拷贝并产生问题吗?

Who will allocate memory for Member structure?谁来为 Member 结构分配 memory?

std::vector will allocate the memory using the allocator that you provided (implicitly, by using the default argument). std::vector将使用您提供的分配器分配 memory(隐式地,通过使用默认参数)。

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.不,您的 class 不包含指针/引用/迭代器,因此没有什么可以被深度复制,也没有问题。

The vector will allocate the necessary memory.该向量将分配必要的 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.对于某些类,您需要编写一个复制构造函数等。但即使您没有在向量中使用 class 也是如此。

For your class however the default copy constructor will work correctly.对于您的 class 但是默认的复制构造函数将正常工作。 The simple rule of thumb is that if your class needs a destructor, then it also needs a copy constructor and an assignment operator.简单的经验法则是,如果您的 class 需要一个析构函数,那么它还需要一个复制构造函数和一个赋值运算符。 This is called the rule of three.这被称为三法则。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM