0

Bjarne Stroustrup, being asked if...

«Can I use "new" just as in Java?»

He answered «Sort of, but don't do it blindly and there are often superior alternatives.» and showed how to do that, with the following code:

void compute(cmplx z, double d)
{
    cmplx z2 = z+d; // c++ style
    z2 = f(z2);     // use z2

    cmplx& z3 = *new cmplx(z+d);    // Java style (assuming Java could overload +)
    z3 = f(z3);
    delete &z3; 
}

I tougth that whatever the language be, the "new" works in the same manner i.e. allocates space for an object and assigns a pointer with the address of that object.

I'm wondering what's the difference (in terms of performence or whatsoever) between:

MyClass *ptr = new MyClass();
...
delete ptr;

and

MyClass& ref = *new MyClass();
...
delete &ref;


Any ideas about this?


Thank you

user7140484
  • 920
  • 6
  • 14
  • `delete &ref` smells like bad code. If one has to type anything like it, they are doing it wrong. As for the general difference between reference and pointer, this is a dupe of a dupe of a dupe. – SergeyA Nov 28 '16 at 20:48
  • 3
    There is no difference, whatsoever, in terms of performance, and I would expect most compilers to spit out identical code for both. The second version is just more convoluted. – Sam Varshavchik Nov 28 '16 at 20:49
  • @SergeyA, can you please post here the link of the other question? Before I post, I searched and found nothing. – user7140484 Nov 28 '16 at 20:52
  • @SergeyA, ok, I already read. It's not easy to catch all questions posted before even with the sugestions that the site points. – user7140484 Nov 28 '16 at 20:56
  • @SamVarshavchik, thank you for your answer. «I would expect most compilers to spit out identical code for both» is a smart observation not obvious to all people. – user7140484 Nov 28 '16 at 21:03
  • It is certainly obvious to me. The code does exactly the same thing: why would the compiler do anything different? – user207421 Nov 28 '16 at 21:14
  • @EJP, **1)** cout << ++x; **2)** cout << x+1; are you **100% certain** that **ALL** compilers generate the same code? – user7140484 Nov 28 '16 at 21:22

0 Answers0