将对象添加到列表而不调用析构函数

时间:2016-10-20 08:32:18

标签: c++11 vector destructor

我想将Foo对象添加到std::vector,但我不想创建一个临时对象来添加到向量中,因为一旦该对象调用Foo::~Foo()临时对象超出范围。我是否必须使用new并使向量存储Foo指针,还是有另一种方式?

想要做的事情:

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

这些会有用吗?

//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?

1 个答案:

答案 0 :(得分:2)

您的两个解决方案都将涉及创建临时解决方案。您可以使用emplace_back代替push_back来构建Foo实例,而不是将其复制到矢量中。

void FooHandler::AddFoo(int a, int b, int c) {
    vectorOfFoos.emplace_back(a,b,c);
}