Allocate memory with pointer or reference?

Asked

Viewed 73 times

3

Is there any significant difference between these two methods?

MyClass &ref = (*(new MyClass));
MyClass *ptr = (new MyClass);

1 answer

2


If you print already see a difference:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string &ref = *new string("teste");
    //string &ref2 = nullptr;
    string *ptr = new string("teste");
    cout << ref << endl;
    cout << ref.length() << endl;
    cout << ptr->length() << endl;
    cout << &ref << endl;
    cout << ptr;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

The pointer is not converted automatically and what you are ordering is to print its value, that is an address, and to take the actual data is not something so simple.

It can also be observed that to access a member by reference use the operator . and for the pointer the -> that makes the melt automatically.

The reference is receiving the value of string and not a pointer, note that had to do the melting, is not storing in the variable even the same thing, so the comparison is oranges with bananas. And I don’t know if I should accept it, but you do.

If the allocation fails it will come a null and a reference does not accept null value in, normal conditions. I even think something should be prohibited, so do not use.

A reference is a const * and cannot be changed, a pointer is free.

Don’t use pointers or references unnecessarily. I know this is an exercise, but in this case it was needless. If you were to do something real you would never do it, then we are evaluating something that you can do, not that you should. Just use what you can justify.

This is a case that is only disguising the use of a pointer, because the new returns a pointer and not a reference. So do not use it for this. Reference is useful when they are created on their own, when the data is in the stack. Just because it works doesn’t mean you should use.

See more in What is the difference between pointer and reference?. Is also useful: When to choose whether to use a pointer when creating an object?. And yet: Where C pointers are actually used++?.

I didn’t even say it’s better wear a smart Pointer (see more) in place of raw pointer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.