Search code examples
c++shared-ptr

Having trouble with list.push_back and std::shared_ptr


This little snippet is giving me quite some trouble. I just can't figure out what is wrong with it:

m_buttons.push_back(
  std::shared_ptr<std::pair<std::shared_ptr<ShinyButton>, BUTTONTYPE>>(
    std::make_pair(
      std::shared_ptr<ShinyButton>(new ShinyButton(0, 0, 0, 0, "menue_1", "menue_1_glow", 55, 55, 7, 7)),
      START
    )
  )
);

the list has the following definition:

std::list<std::shared_ptr<std::pair<std::shared_ptr<ShinyButton>,BUTTONTYPE>>>

The Error given from the compiler is:

No constructer matches Argument list.


Solution

  • You're trying to initialise a std::shared_ptr<std::pair<X, Y>> with std::make_pair. That is like initialising an int * with an int. Perhaps you meant to use make_shared:

    m_buttons.push_back(
      std::make_shared<std::pair<std::shared_ptr<ShinyButton>, BUTTONTYPE>>(
        std::make_pair(
          std::shared_ptr<ShinyButton>(new ShinyButton(0, 0, 0, 0, "menue_1", "menue_1_glow", 55, 55, 7, 7)),
          START
        )
      )
    );
    

    In fact, with make_shared, you won't even need the make_pair call:

    m_buttons.push_back(
      std::make_shared<std::pair<std::shared_ptr<ShinyButton>, BUTTONTYPE>>(
        std::shared_ptr<ShinyButton>(new ShinyButton(0, 0, 0, 0, "menue_1", "menue_1_glow", 55, 55, 7, 7)),
        START
      )
    );