我想将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?
答案 0 :(得分:2)
您的两个解决方案都将涉及创建临时解决方案。您可以使用emplace_back
代替push_back
来构建Foo
实例,而不是将其复制到矢量中。
void FooHandler::AddFoo(int a, int b, int c) {
vectorOfFoos.emplace_back(a,b,c);
}