在c++中,当我将引用的值赋给对象时会发生什么?
What happens when I assign an object the value of a reference in C++?
#include <iostream>
void test(std::string &s) {
std::string p = s;
std::cout << p.length() << " " << p;
}
int main() {
std::string s = "Hello world";
test(s);
return 0;
}
因此,函数test
从我的main
函数接收到对字符串s
的引用。
我的问题是,这一行是做什么的:
std::string p = s;
是否浅层复制引用并将其放在p
中,从而违背了最初使用引用的目的?
或者它(p
)只是作为一个参考?
它创建了引用值的副本,它不允许您用p
编辑s
的内容,为了使p
作为引用并能够从p
编辑s
,您必须将其声明为引用:
std::string& p = s;
因此违背了最初使用引用的目的?
为什么它违背了引用的目的,你已经声明了s
作为引用,不是吗?不是p
。如前所述,它将复制s
包含的值
当我在c++中给一个对象赋值时,会发生什么?
不能给引用赋值,或者至少不应该这样考虑。引用不是指针。因为引用是通过不同的名称访问的对象,所以给对象赋值。
void test(std::string &s) {
处理引用的事实只在声明点真正相关。该函数中所有使用s
的代码都使用std::string
,而不是std::string &
。
我的问题是,这一行是做什么的:
std::string p = s;
它将你的std::string
对象赋值给p
,不多也不少。换句话说,它的作用与下面程序中的相同:
int main() {
std::string s = "Hello world";
std::string &s_with_different_name = s;
std::string p = s_with_different_name;
std::cout << p.length() << " " << p;
}
或者更简单地说:
int main() {
std::string s = "Hello world";
std::string p = s;
std::cout << p.length() << " " << p;
}
相关文章:
- 什么时候调用组成单元对象的析构函数
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 是什么让放置新调用对象的构造函数?
- 当 std::move 与 C 样式数组或不移动对象时会发生什么
- 在什么情况下,两个堆栈分配的结构对象的 this 点指向同一个地址?
- 这个C++编译器优化(在自身的实例上调用对象自己的构造函数)的名称是什么,它是如何工作的?
- 什么更好?返回对象指针列表?或返回指向对象列表的指针?
- 在什么条件下使用 std::memcpy 在对象之间复制是安全的?
- 处理影响跨不同线程共享对象的定时回调的最佳方法是什么?
- 具有相同特征的两个对象是否只在内存中存储一次?无论定义它们的函数是什么,都是不同的
- 为对象分配整数.输出将是什么?
- 当使用对象名称后带有 [] 的类对象时,您究竟会传入什么.C++
- 什么是"undetectable means",它们如何更改 C/C++ 程序的对象?
- 在C++中,创建'n'数量的对象的推荐方法是什么,其中n是用户定义的。我该怎么做?
- 使用 gtest 框架在单元测试代码中检查目标对象的私有变量的最佳实践是什么?
- 删除对象(具有不同类型)的引用时会发生什么情况?
- 一个对象什么时候可以有非零大小的一个,但不能同时具有一个或多个字节的存储
- 在C++中,对象什么时候真正被销毁?delete(ptr)做什么
- C++在文件中保存类对象和从文件中读取类对象.什么是最好的选择