[英]C/C++ - copying by value arrays that are part of structs
consider the following C++ struct: 考虑以下C ++结构:
typedef struct Person {
std::string name;
std::string children[MAX_NUM_CHILDREN];
} Person;
The question is, what happens in the following scenario: 问题是,在以下情况下会发生什么:
void do_something(const Person& p) {
Person person_copy = p;
}
The question is whether the children
array of p
, which is actually a member of type std::string*
, is going to be copied as a pointer, or is every string in the children
array going to be copied by value using the copy constructor? 问题是
p
的children
数组是否实际上将是std::string*
类型的成员,将被复制为指针,还是将使用copy构造函数按值复制children
数组中的每个字符串? ?
[...] the
children
array ofp
, which is actually a member of typestd::string*
[...][...]
p
的children
级数组,实际上是std::string*
类型的成员[...]
children
is an array of MAX_NUM_CHILDREN
strings, not a pointer. children
是MAX_NUM_CHILDREN
字符串的数组,而不是指针。 All of its elements will be copied over to person_copy.children
by Person
's copy constructor. Person
的copy构造函数会将其所有元素复制到person_copy.children
。
I don't think there the array will decay in this example so the content will be copied. 我不认为在此示例中数组会衰减,因此内容将被复制。
T[]
and T*
are different but T[]
can decay to T*
(you can look for the array decaying rules). T[]
和T*
不同,但是T[]
可以衰减到T*
(您可以查找数组衰减规则)。
Your Person
struct should be declared like that: 您的
Person
结构应该这样声明:
struct Person {
std::string name;
std::string children[MAX_NUM_CHILDREN];
};
That's shorter and that's the C++ way. 那更短,这就是C ++的方式。
BTW, the copy constructor will be called because this is an assignment initialisation but it's better use the Person p(p2);
顺便说一句,将调用复制构造函数,因为这是一个赋值初始化,但最好使用
Person p(p2);
(or Person p{p2}
with C++11 compatible compiler) initialisation form. (或具有C ++ 11兼容编译器的
Person p{p2}
)初始化表格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.