简体   繁体   中英

-> operator not allowed on statically allocated objects in C++?

I'm a self-taught programmer taking a formal college programming course for the first time. Today someone asked the instructor in a C++ class what the -> operator does.

The instructor said something along the lines of "the arrow operator is the equivalent of the dot operator except for dynamically allocated objects. You can only use the dot operator on statically allocated objects [followed by an example of declaring variables at the beginning of a block], and you can only use the arrow operator on dynamically allocate objects you made with new ."

C++ is absolutely not my area of expertise... but every other thing I've looked at said a->b is exactly equivalent to *ab , and that it existed mainly for legacy reasons because variables worked differently in early versions of C++.

Is it true that -> cannot be used on pointers to objects that are allocated on the stack, and that . cannot be used on dereferenced pointers to objects allocated on the heap?

Your instructor's answer is not correct, it generalizes for some usual basic cases but it also shows that he or she does not really have any experience in writing larger projects in C++. Here is why:

If you allocate objects on the stack, ie use the automatic memory of C++, you would usually do something like:

SomeClass object;
object.doSomething();

If you allocate the memory on the heap, it would usually look like this:

SomeClass* object = new SomeClass; // unique_ptrs are a better way but this might be easier to grab for now
object->doSomething();
delete object;

But you might also refer to object via a reference, so that . works again. And you might have a pointer that refers to your object that has been allocated on the stack or the heap, thus accessing with -> works.

All in all, . is used to access non-pointers and -> is used to access pointers. Also, there might be classes that have operator-> overloaded. Then, you can also access a non-pointer instance of a class with that operator.

a->b (assuming no overload changing its semantics) is (*a).b .

How *a was allocated is entirely irrelevant.

The following is legal, valid and safe (if a little stupid):

std::string* str = new std::string("abc");
std::string& ref = *str;

const int n = ref.size();
// oh no! used dot on dynamically-allocated object!

The teacher is wrong.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM