Sunday 15 February 2015

Returning an object from a function C++ -


Let's say that I have a variable that I have indicated for an object. For this example, suppose That I have an object that represents a card, which has 2 members - rank and suit.

Next, when I said I started that object structure, so now I have a card object with rank and suit.

My question is, should I have a function that I created the object of this card: I want to do something like this:

  Card * PlayerCard = foo ()   

I know that the player is pointing to the card card object, does it mean that the FU () also has to return the card object? Is there another way for this problem?

Actually I want to make my work card and the player card should be equal to what is generated. I do not know if it is the most straightforward approach to returning a problem to return the problem, so I am asking whether there is any alternative solution.

Thanks for the help!

I'm progressively going from bad to good way

First of all, there is a wrong way to do this:

  card * foo () {card C; Return and C; }   

Definitely do not do this card c at the end of foo And therefore the returning indicator will point to the invalid object.

You can

  card * foo () {return the new card}; }   

The card made by the new card () is the dynamic storage period, so it is not destroyed at the end of foo The returned indicator is still pointing to that card. Then you can use the pointer and can be safe.

However, there is another negative side of it, it is not clear to the person who calls foo , but they delete to return to the indicator Code> to ensure that there is no memory leak, instead it is best to use smart pointer to pass the ownership to the caller:

  std :: Unique_ptr & lt; Cards & gt; Foo () {return std :: unique_ptr & lt; Cards & gt; (New card ()); }   

However, if you do not need dynamic allocation at all then it is even better. Why not only return card and copy it from function? You can do this:

  card fu () {return card (); }   

Instead of specifying a pointer, you can call the function like this:

  card c = foo ();   

It definitely depends on your needs. If you want to use card * polymorphically, then you have to use an indicative approach. Otherwise you will end up breaking your card derivatives.

No comments:

Post a Comment