简体   繁体   中英

Accessing an element in a vector of pointers to classes?

I have a vector containing pointers to several classes. The classes are defined as so:

class trackerSocket{
public:
    ~trackerSocket();

    int trackerInitialize(string address);
    int trackerSend(string getParams);
    int trackerRecv();

    be_node *responseDict;
    bool working;
    unsigned int interval;
    string trackerid;
    unsigned int complete;
    unsigned int incomplete;
    be_dict *peersDict;
    string peersBinary;
    bool dictionary;

private:
    string address;
    string port;
    string protocol;
    string page;
    SOCKET ConnectSocket;

    int parseAnnounce(string announce);
    int parseTrackerResponse(string response);
};

the vector is declared by this line:

vector<trackerSocket*> trackers;

and the classes are added to the vector using this line:

trackerSocket *temptracker = new trackerSocket();
//Initialize values in temptracker structure here (omitted)
trackers.push_back(temptracker);
//Reset temptracker
temptracker = new trackerSocket();
//Initialize values in temptracker structure here (omitted)
trackers.push_back(temptracker);
//Repeat

How can I access the working variable of each class in the vector? The following code does not print working at all even though I know some of the classes have it set to true.

for(i = 0; i < trackers.size(); i++){
    if(trackers[i]->working){
        printf("Working.\n");
    }
}

Thanks for your help :)

Try switching the line where you are allocating memory and the line where you are using push_back(). Insertion may invalidate pointers in std::vector.

Pointers to elements of std::vector and std::list

If think issue may be in scope in which initialization of instances of classes is perofrmed. As I know instances and therefore their members are initialized by zero values in namespaces, in static and in global scope, if you create instances of object on one of this scope this can lead to that filed working is init by default value "0" and I don`t wonder why

for(i = 0; i < trackers.size(); i++){
    if(trackers[i]->working){
        printf("Working.\n");
    }
} 
not working as you expect. If so I offer you to use default constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM