samedi 29 octobre 2016

Getting around copy semantics in C++

Please consider this code:

class A
{

};

int main()
{
    std::vector<A> test;
    test.push_back(A());
}

The constructor and destructor will be called twice, also memory will be allocated twice and the object will copied, now not only is that potentially bad for performance it could also lead to run time errors, especially if there's some cleanup going on in the destructor. The way i'd usually get around this is to just create a vector of pointers instead :

std::vector<A*> test;
test.push_back(new A());

My question is two fold, is this common practice and is it good practice? Or is there a better way? If this turns out to be a dupe please let me know and i'll close the question, but I couldn't find anything on searching.

Aucun commentaire:

Enregistrer un commentaire