samedi 28 septembre 2019

Avoid copying in returning current object

The following code implements a methods that either returns a copy of its corresponding object or creates a new object and returns it based on the value of cond. Ideally, I wish to change it in a way that if cond is true, the method returns it's object not a copy of it.

#include <iostream>
#include <vector>
class Base {
protected:
std::vector<int> p_;
public:
    Base(std::vector<int> p) : p_(p.begin(), p.end()) {}
    Base getObj() const {
        if (cond) {
            return *this; // Even if cond is true, I'm copying here. This is what I wish to change.
        } else {
            std::vector<int> p1 = {...};
            return Base(p1);
        }
    }
};



int main() {
    std::vector<int> v = {2, 4, 5};
    std::vector<Base> objects;
    Base b(v);
    objects.emplace_back(b.getObj());
}

More Details

I'm flexible to change the return type of getObj to reference or pointer. Nonetheless, I cannot change this vector that holds the output: std::vector<Base> objects;

Aucun commentaire:

Enregistrer un commentaire