[英]What happens when assigning passed-by-reference variable to struct member
I defined this struct
: 我定义了这个
struct
:
template<class T>
struct Node {
T value;
Node(const T& v) : value(v) {}
};
I want to know what exactly happens when I do 我想知道我做什么时会发生什么
int i = 3;
Node<int>* my_node = new Node<int>(i);
By printing out the address of i
and the address my_node->value
I realized that they don't refer to the same address. 通过打印出
i
的地址和my_node->value
的地址,我意识到它们没有引用相同的地址。 I did expect this behavior because it doesn't make sense to force my new pointer to be placed at a specific address, to be able to wrap my passed-by-reference argument!!! 我确实期望这种行为,因为强行将我的新指针置于特定地址并能够包装我的按引用传递参数没有意义!!!
But I'm wondering what's the role of &
? 但是我想知道
&
的作用是什么? Is it just to make sure argument is not copied when passed to the method? 只是为了确保传递给方法时不会复制参数吗? And if yes, is that just to avoid heavy copying?
如果是,那是否只是为了避免大量复制? Or is there another purpose for using
&
? 还是使用
&
还有其他目的?
And value(v)
or value = v
simply copy the whole datatype into a new memory space, no matter if v
is passed by reference or not, am I right? 而且
value(v)
或value = v
只是将整个数据类型复制到一个新的内存空间中,无论v
是否通过引用传递,对吗?
Edit: I'm sorry I tried to shorten my code and ended up making it ambiguous. 编辑:对不起,我试图缩短代码长度并最终使其模棱两可。 Just fixed it.
修复它。
This statement is badly formed: Node* my_node = new Node(i); 该语句的格式不正确:Node * my_node = new Node(i);
But I'm wondering what's the role of &?
但是我想知道&的作用是什么? Is it just to make sure argument is not copied when passed to the method?
只是为了确保传递给方法时不会复制参数吗? And if yes, is that just to avoid heavy copying (in case of a big datatype other than int in this example)?
如果是,那是否只是为了避免大量复制(在本示例中为int以外的大数据类型的情况下)? Or is there another purpose for using &?
还是使用&还有其他目的?
The role of & in this case is exactly as you have said. 在这种情况下,&的作用与您所说的完全相同。 The general rule of thumb that I use, is to pass built-ins (eg int, double) by value and pass everything else by const reference to avoid unnecessary copying.
我使用的一般经验法则是按值传递内置函数(例如int,double),并按const引用传递其他所有东西,以避免不必要的复制。
And value(v) or value = v simply copy the whole datatype into a new memory space, no matter if v is passed by reference or not, am I right?
而且value(v)或value = v只是将整个数据类型复制到一个新的内存空间中,无论v是否通过引用传递,对吗?
That is correct also. 那也是正确的。 But for non-built-ins, these two statements differ when used in a constructor.
但是对于非内置程序,这两个语句在构造函数中使用时有所不同。 The first is initialization and is done in the initialization list (which you have done in your example), the latter is assignment and is done in the constructor body.
第一个是初始化,并在初始化列表中完成(在示例中已完成),第二个是赋值,并在构造函数主体中完成。 For non-built-ins, it is generally more efficient to use the initialization list.
对于非内置插件,使用初始化列表通常会更有效。 Otherwise, the object is default initialized before you do the assignment.
否则,将在执行分配之前默认初始化对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.