在不调用析构函数的情况下将对象添加到列表
Adding object to list without calling destructor
我想将 Foo
对象添加到 std::vector
,但我不想创建一个临时对象来添加到矢量,因为一旦临时对象超出范围。我必须使用 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?
您的两个解决方案都涉及创建临时文件。您可以使用 emplace_back
而不是 push_back
就地构建 Foo
实例,而不是将其复制到向量中。
void FooHandler::AddFoo(int a, int b, int c) {
vectorOfFoos.emplace_back(a,b,c);
}
我想将 Foo
对象添加到 std::vector
,但我不想创建一个临时对象来添加到矢量,因为一旦临时对象超出范围。我必须使用 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?
您的两个解决方案都涉及创建临时文件。您可以使用 emplace_back
而不是 push_back
就地构建 Foo
实例,而不是将其复制到向量中。
void FooHandler::AddFoo(int a, int b, int c) {
vectorOfFoos.emplace_back(a,b,c);
}