Add pointer to an Std:vector

Asked

Viewed 383 times

0

Hi, need to add in a vector<TimedCommand> tCommands; access references for Timedcommand instances, example:

    TimedCommand command1("*.*.*.*.*.*",&sonCommand,"13"); 
    (...)
    tCommands.push_back(&command1);

Unfortunately, when I do this happens one no matching function for call to 'std::vector<TimedCommand', std::allocator<TimedCommand>>:: push_back(TimedCommand*)

I’m using the lib Standard C++ for Arduino and Arduino Cron Library. What am I doing wrong?

  • 2

    I think your problem is with typing. You expect to receive a Timedcommand object, and when you pass the reference you are passing a Timedcommand*.

1 answer

1


Are you trying to add a pointer to a std::vector of "normal objects".

std::vector<TimedCommand> tCommands;
TimedCommand command1(...);
tCommands.push_back( &command1 ); //Erro de compilação

The last line tries to convert a TimedCommand* in TimedCommand, which is invalid.

You have two options: change your std::vector to store pointers

std::vector<TimedCommand*> tCommands;
TimedCommand *command1 = new TimedCommand(...); //Alocação dinâmica
tCommands.push_back( command1 ); 

This implies manual memory management, or adding a copy of your variable to std::vector:

std::vector<TimedCommand> tCommands;
TimedCommand command1(...);
tCommands.push_back( command1 ); 

Which may or may not invalidate some logic of your algorithm.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.