user2146414
user2146414

Reputation: 1038

Auto and reference

I've got the following classes:

class Card {
    void rotate();
};
class Type1Card : public Card {};
class Type2Card : public Card {};

class Deck {
    Card& draw_card();
};

class Board {
    std::vector<Card const*> cards;
    void put_card(Card const&);
};

So the Deck manages cards. It returns reference to a card. Then a card can be put on a board - using const reference to indicate that it cannot be nullptr nor change. As you can see the Board stores pointers to cards (because of polymorphizm).

The problematic code:

auto card = deck.draw_card(); // a copy of a card is created
card.rotate();
board.put_card(card); // board will get a pointer to a temporary variable

The solutions I see:

  1. draw_card returns a pointer - ugly because I believe that pointer is to indicate that nullptr can be returned - not true
  2. put_card gets a pointer - the same as above why not
  3. disable a Card's copy constructor - ugly because it's not a problem of the Card - no reason to limit the Card class

Upvotes: 1

Views: 108

Answers (2)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

It is enough to use auto&:

auto& card = deck.draw_card();

so the reference won't be discarded during the type deduction.


Also, please, note, that using a std::vector of raw pointers:

std::vector<Card const*> cards;

is not the best idea. As your cards come to Board outside, Board itself does not control the lifetime of the cards it refers to. In this case it is extremely easy to get dangling pointers and move to the UB area.

You should probably consider just copying cards to the Board class or start using smart pointer - whatever suits better to your program.

Upvotes: 2

user9212993
user9212993

Reputation:

You can tell auto variables to be references, just write

auto& card = deck.draw_card();

same for const reference

const auto& card = deck.draw_card();

Upvotes: 2

Related Questions