c++ - 传递参数、列表和复制构造函数 C++

标签 c++ list parameter-passing copy-constructor

我在考试中遇到了这个问题

In a passing parameter, during a function call, the parameters are copied => call to the copy constructor for each parameter. Suppose a List is passed as a parameter, all the elements of the list are copied. If it is a reference to a list, only the address of the list is copied. What's your say about those statements?

我的回答是“如果它是对列表的引用,则不仅复制地址而且复制值”,我得到 5 分(满分 10 分)。 我的回答错了吗?对我来说,这就是我得到的。以上说法正确吗?

最佳答案

如果通过引用传递,则不会创建对象的拷贝。这就是按引用传递和按值传递之间的区别。

在幕后,引用被实现为指针,所以你可以说地址被复制了,但那是一个实现细节。

虽然公式是错误的:

Suppose a List is passed as a parameter, all the elements of the list are copied. If it is a reference to a list, only the address of the list is copied.

传递列表或对列表的引用并不重要。重要的是该方法如何获取参数 - 通过值或通过引用:

void foo(list l);
void goo(list& l);

list x;
list& y = x;

foo(x);  //pass a list by value          --copy is made
foo(y);  //pass a reference by value     --copy is made

goo(x);  //pass a list by reference      --no copy of the list
goo(y);  //pass a reference by reference --no copy of the list

关于c++ - 传递参数、列表和复制构造函数 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13247393/

相关文章:

c++ - 我如何迭代作为指针传递的对数组参数?

Ubuntu 的 C++ 更新框架

c++ - Qt VideoWidget 示例

c++ - 组织外部库和包含文件

java - 如何将数字放入通用列表中?

python - 需要帮助在列表的每个值之间插入值

python - 如何将 pandas 方法作为参数传递?

java - 静态实例变量按值传递

c++ - 如何获取类成员函数指针

c# - 在 List<T> 和 IEnumerable<T> 之间自由转换