C++ 在C+中传入vs分配常量引用+;
我们有常数参考x:C++ 在C+中传入vs分配常量引用+;,c++,reference,variable-assignment,C++,Reference,Variable Assignment,我们有常数参考x: 传递到函数B,所以基本上我们复制x的值,然后传递到函数B?(否,取决于x是否为参考) 将x赋值给str,那么这里我们还要复制x的值?或者我们只是分配参考 ======================= 是的,我理解函数b(x),它将取决于传入x的是字符串还是字符串&。我现在的困惑仍然是关于作业的第二个困惑 如果我们有这样的东西: const string& x = functionA(); functionB(x); // depends on x is strin
const string& x = functionA();
functionB(x); // depends on x is string or const string&
string str = x;
obj已经创建,我们只是将x分配给obj的字段A。那么这里的x是副本还是参考
顺便说一下,引用的行为与指针非常接近。 类似于有:
在这行中:
string str=x代码>
您正在初始化(创建)字符串“str”,方法是将引用“x”保存的值传递给它的构造函数(不要与赋值混淆,因为str是在这一行创建的),并且由于移动语义导致构造函数分离,因此您将在这里通过const引用将“x”传递给“str”的构造函数,以复制它。
这
obj.fieldA=x
表示您已经创建了,比如说,对象obj代码>
据此,语句obj.fieldA=x代码>将只是复制“x”。
也许我不明白你的最后一个问题,但假设fieldA也是“字符串”类型
然后,当您编写obj.fieldA=x时代码>,将调用类似(非常糟糕的示例,只是为了简化):
这意味着此函数获取了“x”的地址并复制了它的数据。
总而言之:
string& operator=(const string& other){
..
this->str_pointer = new char[other.size() + 1];
strcpy(this->str_pointer, other.str_pointer);
..
}
string first=“text”;
常量字符串&x=first;//x的行为就像一个指针,并保持“first”的地址
对象对象对象;
obj.fieldA=x;//需要查看如何声明functionB
来回答问题。如果functionB的参数为“const string&”,则不会复制任何副本,因为您正在将addr传递给原始字符串。如果删除ref,则函数将创建一个副本。
void func(int val);
int a = 11;
int *ptr = &a;
func(*ptr); // same as functionB(x);
string& operator=(const string& other){
..
this->str_pointer = new char[other.size() + 1];
strcpy(this->str_pointer, other.str_pointer);
..
}
string first = "text";
const string& x = first; // x behaves just like a pointer and holds address of 'first'
Object obj;
obj.fieldA = x; // <--- here