Is there drawback in declaring and defining variable at return?
Here is one case from the user Man in Black's question. If we return a reference to a local variable, we will end up with an incorrect value. The reason is that the local variable would be destroyed upon returning.
One of solution is using "shared_ptr" like this by the user Christophe:
struct node {
int data;
node* next;
};
shared_ptr<node> create_node(int value) {
node* newitem = new node;
newitem->data=value;
newitem->next=NULL;
return (shared_ptr<node>(newitem));
}
This is a concise solution, but at the returning code line, it declare and define variable of "shared_ptr(newitem)".
This is declaring variable, temp, and then define it:
shared_ptr<node> temp; // Declare variable
temp = shared_ptr<node>(newitem); // Define variable
return temp;
I am trying to avoid memory allocation failure. Would we say this is better in the case of failing memory allocation?
return (shared_ptr<node>(newitem));
creates an object of ashared_ptr
type, no declaration or definition here. – Gnninewitem
to a certain pointer; that's a variable. There is no name associated with the result ofshared_ptr<node>(newitem)
; that's not a variable. – Gnnishared_ptr<node> temp;
both declares and defines a variable. The linetemp = shared_ptr<node>(newitem);
assigns a value to (almost initializes) the variable; there is no definition at this point. – Gnnishared_ptr<node> temp
is also defining, what we will see when we call the "temp"? Isn't random value from unknown memory location? – Jolynjolynnshared_ptr<node>
temp is also defining, what we will see [...] -- This question is off-base, because defining a variable does not mean giving it a value; defining a variable means providing space for a value. See What is the difference between a definition and a declaration? and its follow-up What distinguishes the declaration, the definition and the initialization of a variable? – Gnniconst
variable must be initialized, in other words assigned a value, in the same statement in which it's defined. (The sentence after that one is also incorrect. A declaration of a built-in type such as int is not automatically a definition. The declarationextern int i;
is not a definition.) – Gnni