Vector of pointers: Push back objects/const parameters
Apr 11, 2014 at 3:51pm UTC
I have a class called Question:
1 2 3 4
#include <string>
#include <vector>
using namespace std;
1 2 3 4 5 6 7 8
class Question {
string title;
vector<Thing*> posAns;
vector<Thing*> negAns;
public :
Question(const string&);
void AddThing(const Thing&, const char &);
};
1 2 3 4 5 6 7 8 9 10 11
void Question::AddThing(const Thing& thing, const char & answer) {
switch (answer) {
case 'Y' :
posAns.push_back(&thing); //error
break ;
case 'N' :
negAns.push_back(&thing); //error
break ;
}
}
error: no instance of overloaded function 'std::vector::push_back()' matches the arguments list
argument types are (const Thing *)
object type is: std:: vector<Thing *, std::allocator<Thing *>>
So it cannot be constant, what if I just leave it non-constant? Will it be safe?
Apr 11, 2014 at 3:58pm UTC
Only as safe as your code.
Why are you pushing pointers? This is a practice that should be avoided unless absolutely necessary. It opens up the possibility of memory leaks.
Why not simply declare posAns and negAns as
vector<Thing>
? Then you won't have a possibility of memory leaks or the const issue.
Apr 11, 2014 at 4:02pm UTC
I'm making a 20 question style game. The pointers are for AI purpose. I haven't known are the pointers neccessary yet. So...
Topic archived. No new replies allowed.