'&' 是什么意思在 C++ 声明中做什么?

2021-12-29 00:00:00 operators syntax c++

我是一个 C 人,我正在尝试理解一些 C++ 代码.我有以下函数声明:

I am a C guy and I'm trying to understand some C++ code. I have the following function declaration:

int foo(const string &myname) {
  cout << "called foo for: " << myname << endl;
  return 0;
}

函数签名与等效的 C 有何不同:

How does the function signature differ from the equivalent C:

int foo(const char *myname)

使用 string *mynamestring &myname 有区别吗?C++ 中的 & 和 C 中的 * 表示指针的区别是什么?

Is there a difference between using string *myname vs string &myname? What is the difference between & in C++ and * in C to indicate pointers?

同样:

const string &GetMethodName() { ... }

& 在这里做什么?是否有一些网站解释了 & 在 C 和 C++ 中的使用方式不同?

What is the & doing here? Is there some website that explains how & is used differently in C vs C++?

推荐答案

&"表示引用而不是指向对象的指针(在您的情况下为常量引用).

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

拥有

foo(string const& myname) 

结束

foo(string const* myname)

是在前一种情况下,您可以保证 myname 是非空的,因为 C++ 不允许 NULL 引用.由于您是通过引用传递,因此不会复制对象,就像传递指针一样.

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

你的第二个例子:

const string &GetMethodName() { ... }

允许您返回对例如成员变量的常量引用.如果您不希望返回副本,并且再次保证返回的值是非空的,这将很有用.例如,以下内容允许您直接进行只读访问:

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
  public:
  int bar() const {return someValue;}
  //Big, expensive to copy class
}

class B
{
public:
 A const& getA() { return mA;}
private:
 A mA;
}
void someFunction()
{
 B b = B();
 //Access A, ability to call const functions on A
 //No need to check for null, since reference is guaranteed to be valid.
 int value = b.getA().bar(); 
}

您当然必须小心不要返回无效的引用.编译器会很乐意编译以下内容(取决于您的警告级别以及您对待警告的方式)

You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
 int a;

 //This is very bad, returning reference to something on the stack. This will
 //crash at runtime.
 return a; 
}

基本上,您有责任确保返回的引用实际上有效.

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

相关文章