Variable/pointer scope (rookie Qs)
I have 3 pieces of code below. A simple one really - just need to know which ones are safe. I think A and maybe C is safe. However, B is dangerous from my experience, but I'm not exactly sure why as the memory inside has been allocated to the heap, so it should last 'forever', and not just be local to the function.
Code:
// A: I think this is safe:
#include <iostream>
struct prvs { int quantity; };
prvs* pr() {
prvs* p = new prvs; p->quantity=3;
return p;
}
int main(int argc, char**argv)
{
prvs* prv = pr();
}
// B: I think this is dangerous:
#include <iostream>
struct prvs { int quantity; };
prvs pr() {
prvs* p = new prvs; p->quantity=3;
return *p;
}
int main(int argc, char**argv)
{
prvs* prv = &pr(); // Will this pointer's contents always survive?
}
// C: I'm not so sure about this one
#include <iostream>
struct prvs { int quantity; };
prvs pr() {
prvs* p = new prvs; p->quantity=3;
return *p;
}
int main(int argc, char**argv)
{
prvs prv = pr();
}