简体   繁体   中英

Why can't I add items into my vector?

I have the following code in one class:

    class A
    {
        std::vector<Parameter*> params;
        std::vector<Parameter*> getParamVector() {return params;}
        void addOneParam(Parameter* param)
        {
            params.push_back(param);
        }
    }

In another class, class B , I try to add items into the params vector by doing this:

classA_Ptr->getParamVector().push_back(aParamPtr);

But the params vector's size still 0, after above call.

I have to add above addOneParams(Parameter* param) method to add items into the params vector. Why?

getParamVector() returns a copy of params . So when you push_back onto it, you're adding to a temporary vector that gets deleted right away. That in no way affects params 's size.

If you want to be able to do this via getParamVector() , you'll have to return a reference to params instead:

std::vector<Parameter*>& getParamVector() {return params;}
                      ^^^

You should return either by reference or pointer as pointed out.

std::vector<Parameter*>& getParamVector() { return params; }

or

std::vector<Parameter*>* getParamVector() { return &params; }

But, here is the real question: if you already have a method that can add one parameter, why do you need to call getParamVector().push_back().

Instead, you could just do classA_ptr->addOneParam(p).

EDIT: To me addOneParam() enforces data hiding better than getting a reference/pointer to the internal vector.

If the data structure to store the parameters changes, the caller will need to be modified as well.

With addOneParam(), the caller is insulated.

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