什么是'&'在C ++声明中? [英] What does '&' do in a C++ declaration?

查看:166
本文介绍了什么是'&'在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)


b $ b

使用 string * myname vs string& 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() { ... }


b $ b

允许你返回一个常量引用,例如,一个成员变量。如果您不希望返回副本,并且再次确保返回的值非空,这将非常有用。例如,以下内容允许您直接,只读访问:

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.

这篇关于什么是'&amp;'在C ++声明中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆