jeudi 20 octobre 2016

C++ - Adding object to list without calling destructor

I want to add a Foo object to a std::vector but I don't want to create a temporary object to add to the vector because that would call Foo::~Foo() once the temporary object goes out of scope. Do I have to use new and make the vector store Foo pointers, or is there another way?

What I don't want to do:

void FooHandler::AddFoo(int a, int b, int c) {
    Foo foo(a, b, c);
    vectorOfFoos.push_back(foo);
} //foo goes out of scope so Foo::~Foo() is called

Would these work?

//Foo has an implicit constructor which takes a FooSettings object
struct FooSettings {
public:
    int a;
    int b;
    int c;
};

void FooHandler::AddFoo(int a, int b, int c) {
    vectorOfFoos.push_back(Foo(a, b, c));
} //is Foo::~Foo() called here?

void FooHandler::AddFoo(FooSettings settings) {
    vectorOfFoos.push_back(settings);
} //is Foo::~Foo() called here?

Aucun commentaire:

Enregistrer un commentaire