More effective C + +: The difference between pointers and references

Source: Internet
Author: User

The pointer looks completely different from the reference (the pointer uses the operator ' * ' and '-> ' to refer to the operator '. ') ), but they seem to have the same functionality. Pointers and references allow you to indirectly refer to other objects. How do you decide when to use the pointer and when to use the reference?

First, realize that you cannot use a reference to a null value under any circumstances. A reference must always point to some object. So if you use a variable and let it point to an object, but the variable may not point to any object at some point, you should declare the variable as a pointer, because you can assign a null value to the variable. Conversely, if the variable definitely points to an object, for example, your design does not allow the variable to be empty, then you can declare the variable as a reference.

"But wait a minute," you asked suspiciously, "what kind of consequences would such a code have?" ”

char *pc = 0; // 设置指针为空值
char& rc = *pc; // 让引用指向空值

This is very harmful, no doubt. The result will be indeterminate (the compiler can produce some output that could cause anything to happen) and should avoid people who write such code unless they agree to correct the error. If you're worried that the code will appear in your software, you'd better avoid using references altogether, or you can get better programmers to do it. We will later ignore the possibility of a reference pointing to a null value.

Because the reference will definitely point to an object, in C, the reference should be initialized.

string& rs; // 错误,引用必须被初始化
string s("xyzzy");
string& rs = s; // 正确,rs指向s

The pointer has no such restriction.

string *ps; // 未初始化的指针
// 合法但危险

The fact that there is no reference to a null value means that the code that uses the reference is more efficient than using the pointer. Because you do not need to test the legality of a reference before using it.

void printDouble(const double& rd)
{
cout << rd; // 不需要测试rd,它
} // 肯定指向一个double值

Instead, the pointer should always be tested to prevent it from being empty:

void printDouble(const double *pd)
{
if (pd) { // 检查是否为NULL
cout << *pd;
}
}

Another important difference between pointers and references is that pointers can be assignable to point to another different object. However, references always point to objects that are specified at initialization time and cannot be changed later.

string s1("Nancy");
string s2("Clancy");
string& rs = s1; // rs 引用 s1
string *ps = &s1; // ps 指向 s1
rs = s2; // rs 仍旧引用s1,
// 但是 s1的值现在是
// "Clancy"
ps = &s2; // ps 现在指向 s2;
// s1 没有改变

In general, you should use pointers in the following situations, one is that you take into account the possibility of not pointing to any object (in this case, you can set the pointer empty), and the second is that you need to be able to point to different objects at different times (in which case you can change the direction of the pointer). If you always point to an object and do not change direction once you point to an object, you should use a reference.

In another case, when you overload an operator, you should use a reference. The most common example is the operator []. The typical use of this operator is to return a target object, which can be assigned a value.

vector v(10); // 建立整形向量(vector),大小为10;
// 向量是一个在标准C库中的一个模板
v[5] = 10; // 这个被赋值的目标对象就是操作符[]返回的值

If the operator [] Returns a pointer, the latter statement has to be written like this:

*v[5] = 10;

But this makes v look like a vector pointer. So you will choose to have the operator return a reference.

You should not use pointers when you know that you have to point to an object and you do not want to change its direction, or when overloading the operator and preventing unnecessary semantic misunderstanding. In other cases, you should use pointers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.