C++ 使用对字符串的引用作为别名

C++ Using a reference to a string as an alias

本文关键字:引用 别名 字符串 C++      更新时间:2023-10-16

使用对象的引用作为别名总是安全的吗?例如,一个字符串:

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;
}

是的。它们都指向内存中的同一位置。输出每个变量的地址,您将看到此信息。