C++ 使用对字符串的引用作为别名
C++ Using a reference to a string as an alias
使用对象的引用作为别名总是安全的吗?例如,一个字符串:
std::string test;
std::string &reftest( test );
std::cout << "test before: " << test << "n";
std::cout << "reftest before: " << reftest << "n";
reftest = "abc";
std::cout << "test after: " << test << "n";
std::cout << "reftest after: " << reftest << "n";
是否可以保证 reftest 和 test 始终具有相同的字符串?
如果您将引用视为昵称,这会有所帮助。即使你说的是reftest
,你仍然指的是test
。所以,简而言之,是的。
请注意,存在一些限制。例如,以下内容不是标准的:
std::string &reftest( std::string("test") );
但是这个
const std::string &reftest( std::string("test") );
是,因为常量引用可以绑定到临时引用,而非常量引用不能。
它们是同一个字符串,就像一个叫罗伯特的人叫鲍勃一样。
就像你说的,它只是同一件事的两个名字——一个别名。
是的。这两个名称指的是同一个对象。
虽然名称之间存在一些差异。 例如 decltype(reftest)
不产生与decltype(test)
相同的类型。
正如其他人指出的那样,有一些方法可以获得不合法使用的引用,但在这些情况下,这是因为引用不是合法变量的别名。
在你的例子中是的,但有陷阱:
struct X {
std::string& s;
X(std::string& s) : s(s) {}
};
struct Y {
std::string s;
};
int main() {
Y* y = new Y();
X x(y->s);
delete y;
// now, x.s is dangling, as it refers to y->s, which is gone.
std::cout << x.s << std::endl; // <- segfault
return 0;
}
是的。它们都指向内存中的同一位置。输出每个变量的地址,您将看到此信息。
相关文章:
- 对编译时 C 数组的严格别名和引用
- 强制转换为不相关的引用类型是否违反严格的别名规则?
- 为什么模板引用类型不能用作模板类型别名参数?
- 是否可以将引用类型别名与指针运算符一起使用来声明对指针的引用?
- 为什么模板别名专用化取决于引用它的上下文
- 为什么我可以使用类型别名声明常量引用
- 使用 std::weak_ptr 和别名构造函数中断循环引用:声音或有问题
- 通过引用创建别名以提升:shared_ptr
- 转发引用是否可以使用别名模板进行别名处理
- 身份别名模板是否可以作为转发引用
- 在 C++ 中作为指针或别名进行内部编译的引用
- 修改引用变量,而不是修改它们别名的变量
- clang或gcc是否利用引用限制进行别名分析
- 使用别名引用匿名结构会导致错误
- 使用常量引用为变量设置别名
- Qt 表按名称或别名引用小部件列
- 使用别名将通用引用限制为单个类型
- C++ 使用对字符串的引用作为别名
- 取消引用类型的punned指针将打破严格的别名规则[-Wstrict aliasing]
- C++ : 在左侧常量赋值上添加引用/别名 (&) 是多余的吗?