Solved

any reference returning example

Posted on 2013-05-16
13
316 Views
Last Modified: 2013-05-21
COuld you please fill the below function's body in any appropriate way?
Node is any class.

Node &  f ( Node& x)
{

?
}

IN addition , How will i call it ?

Thanks in advance.
0
Comment
Question by:codeBuilder
  • 4
  • 4
  • 3
  • +1
13 Comments
 

Author Comment

by:codeBuilder
Comment Utility
I wrote as below

Node &  f ( Node& x)
{
    Node nd = new Node();
    return nd;
}

but it gives WARNING :
 warning: reference to local variable ‘nd’ returned [enabled by default]

WHEN i run it, segmentation fault occurs . Why this warning occured?What did i do wrong? What should i do ?
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 200 total points
Comment Utility
You can't return a reference to a local variable - and 'new' is completely off ther, since it creates a pointer, not a reference. Something like

Node &  f ( Node& x)
{
  // change x 

   return x;
} 

Open in new window


would work - that is, without knowing the big picture. Calling that function would be like

Node x, y;

y = f(x);

Open in new window

0
 
LVL 86

Accepted Solution

by:
jkr earned 200 total points
Comment Utility
Oh, what you also could do without a segfault would be

Node &  f ( Node& x)
{
    Node* p = new Node();
    return *p;
} 

Open in new window


but that will create memory leaks.
0
 

Author Comment

by:codeBuilder
Comment Utility
Why does it create memory leaks? Can't i prevent it for the above small code(which you give recently) with little tricks?

In addition , i do such a thing like below:
for(i=0;i<10,i++)
{
Node* p = new Node();
}

Open in new window


Does it have any problem to do such a thing?Where is the problem ?
0
 
LVL 86

Assisted Solution

by:jkr
jkr earned 200 total points
Comment Utility
Because you cannot 'delete' the instance you created with 'new' any longer, that's the reason...
0
 

Author Comment

by:codeBuilder
Comment Utility
Yeah , i understand but what should i do when i need to create pointer for each loop ?
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 86

Assisted Solution

by:jkr
jkr earned 200 total points
Comment Utility
Store them somewhere to depete them later - any STL container would work.
0
 
LVL 28

Assisted Solution

by:pepr
pepr earned 150 total points
Comment Utility
To add, the Node nd = new Node(); as used near the question comes probably from Java. Or better to say, it is usual in Java (or C#), because Java allocates everything on the heap, the new operator returns the reference, and the reference is assigned to the variable of the type. In Java, all variables are the reference variables, and the references are counted (because the garbage colector needs that). (Possibly simplified.)

In C++, variables are not only reference variables, but they can contain also other than reference values. Also because of that and because the C origin (a high-level assembler), C++ makes syntactic difference between the pointer and the reference. While this can be clear from the doc, one has to get used to the differenc if you are used to Java. I mean to think differently (different mental picture).

An object created in C++ without using new sits in local memory of the function. The memory disappears after the return. This way, also the object disappears and the pointer or reference to the local object is invalid.

Also, you should show a bigger fragment of your code. It is likely that the solution is not only to write the for loop. If you can use C++11 code, nicer for loops can be used (similar to Java's, C#, Python,... more readable, less error-prone).
0
 
LVL 32

Assisted Solution

by:sarabande
sarabande earned 150 total points
Comment Utility
in case of a node object the f could create a new node and then make a chain from the object passed to the new object. finally it returns the new node.

Node & chain(Node & n)
{
     n.next = new Node();
     return *n.next;  // return reference to the new node
}

Open in new window


the above code would allocate memory for a new Node but that would not give a leak cause the new Node would be reachable by the next member of the previous Node. so starting from 'head' you could reach any node and also free them (delete) after use.

Sara
0
 

Author Comment

by:codeBuilder
Comment Utility
@sarabande
To do what you said , should i do as the following definition in the Node class or smthing else:

Node{
..
Node * next = Node;
..
}


@pepr

Although i know C++ for 2 years , I still couldn't learn the difference between the reference & and pointer * . I have always been confused about them . I know its basic definitons. However , when i see them in function's paramaters , or function's returning types , i am absolutely puzzled. For example when i see like :
Node& (const *Node , const Network&)

i shocked and don't know what it means ? I need to see and understand vital examples which is simple but includes all of these keywords
0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
@codeBuilder: I highly recommend "Thinking in C++" by Bruce Eckel (http://www.mindview.net/Books/TICPP/ThinkingInCPP2e.html). You can buy the printed version of the two volumes, or you can download the HTML version for free. (There is no on-line HTML version--at least I do not know about any--but you simply download the zip archive, unzip it and launch the .../Volume1/HTML/Frames.html.)

It is nicely written and it is likely you find the answers with a kind of drill/exhaustive examples. Try the  "Complicated declarations & definitions" (your local disk... ThinkingInCpp/Volume1/HTML/Chapter03.html#Heading176 -- I may have older copy, the Heading176 may have moved slightly). When following his explanations, you will understand even the complex cases like (excerpt):
As an aside, once you figure out how the C and C++ declaration syntax works you can create much more complicated items. For instance:

    //: C03:ComplicatedDefinitions.cpp

    /* 1. */     void * (*(*fp1)(int))[10];

    /* 2. */     float (*(*fp2)(int,int,float))(int);

    /* 3. */     typedef double (*(*(*fp3)())[10])();
                 fp3 a;

    /* 4. */     int (*(*f4())[10])();

    int main() {} ///:~

Walk through each one and use the right-left guideline to figure it out. Number 1 says “fp1 is a pointer to a function that takes an integer argument and returns a pointer to an array of 10 void pointers.”

Number 2 says “fp2 is a pointer to a function that takes three arguments (int, int, and float) and returns a pointer to a function that takes an integer argument and returns a float.”

If you are creating a lot of complicated definitions, you might want to use a typedef. Number 3 shows how a typedef saves typing the complicated description every time. It says “An fp3 is a pointer to a function that takes no arguments and returns a pointer to an array of 10 pointers to functions that take no arguments and return doubles.” Then it says “a is one of these fp3 types.” typedef is generally useful for building complicated descriptions from simple ones.

Number 4 is a function declaration instead of a variable definition. It says “f4 is a function that returns a pointer to an array of 10 pointers to functions that return integers.”

You will rarely if ever need such complicated declarations and definitions as these. However, if you go through the exercise of figuring them out you will not even be mildly disturbed with the slightly complicated ones you may encounter in real life.

There is a nice explanation somewhere in the book about how to read the function definitions, but I did not find it now. (You will do ;)
0
 
LVL 32

Expert Comment

by:sarabande
Comment Utility
To do what you said , should i do as the following definition in the Node class or smthing else:

generally, a Node class object points to another (the next or previous) Node. such "pointing" can only made by pointer in c++. therefore, it makes not so much sense to pass Node objects 'by reference' to  a function when only the pointer was needed. so at least at the node level you would pass a Node object by pointer rather than by reference. a new node would not point to a next pointer but would initialize the next member pointer to NULL. so typically you would use a member function like
Node * Node::append(Node * pn)  
{ 
    next = pn; 
    if (pn != NULL)
        pn->prev = this; 
    return this; 
}

Open in new window

to link two nodes together.

Sara
0
 
LVL 28

Expert Comment

by:pepr
Comment Utility
I still couldn't learn the difference between the reference & and pointer *

Technically, both a reference variable and a pointer variable need the memory space 4 bytes (32-bit system) or 8 bytes (64-bit system). The address of the target memory block is stored inside. The target block of memory can store anything -- from a simple built-in type value (say char) to any complex object (data that belongs to the instance of the class).

When accessing the target. When accessing the target object via a pointer variable, you have to explicitly dereference the value using *. When accessing the same object via the reference variable, the dereferencing is automatic. The reference variable behaves as if it was a variable that stores the object itself; there always is one more indirection hidden inside.

Syntactically, working with a reference variable looks exactly the same as working with the variable that stores the object. For working via pointer, you need special syntax.

References are a bit more abstract than pointers. With a pointer, you actually use the stored address that is used explicitly when dereferencing it. The value can also be NULL. With a reference variable, the address is a bit more wraped inside. The stored value cannot be NULL.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now