Are there any significant differences between these two methods?
MyClass &ref = (*(new MyClass));
MyClass *ptr = (new MyClass);
Are there any significant differences between these two methods?
MyClass &ref = (*(new MyClass));
MyClass *ptr = (new MyClass);
If you print, you 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;
}
See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .
The pointer is not automatically converted and what you are prompted to do is to print its value, ie an address, and to get the actual data is not so simple.
It can also be observed that in order to access a member by reference, the .
operator is used and for the pointer the ->
is used that automatically performs the derreference.
The reference is getting the string value and not a pointer, note that it had to do the derreference, it is not storing the same variable in the variable, so the comparison is oranges with bananas. And I do not know if I should accept, but it's a fact that you accept.
If the allocation fails, a null will come and a reference does not accept null value under normal conditions. I think even something that should be banned, so do not use it.
A reference is const *
and can not be changed, a pointer is free.
Do not use unnecessary pointers or references. I know this is an exercise, but in this case it was unnecessary. If I were to do something real I would never do this, then we are evaluating something that can do, not that it should. Just use what you can justify.
This is a case that is only disguising the use of a pointer, because new
returns a pointer, not a reference. So do not use it for this. Reference are useful when they are created by themselves, when the data is in stack . Just because it works does not mean you should use it.
See more in What is the difference between pointer and reference? . Also useful: When should I choose whether to use a pointer when creating an object? . Also: What are pointers used in C ++? .
I did not say that it's better use a smart pointer (see more ) instead of the raw pointer.