【发布时间】:2017-03-02 03:37:13
【问题描述】:
我想将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?
【问题讨论】:
-
出于兴趣,为什么不想调用
Foos 析构函数? -
@ChrisDrew
Foo实际上是 C 库中一些函数的包装器。Foo::Foo()构造函数使用该库中的一个函数来创建动态指针,而Foo::~Foo()析构函数则清理该指针。因此,从Foo实例的任何副本调用析构函数都会删除动态指针。 -
@Tagglink 听起来像
Foo的复制构造函数已损坏。销毁副本通常不应删除另一个对象中的某些资源。我建议使用std::unique_ptr而不是手动管理资源。 -
@TartanLlama 智能指针的问题是我需要从库中调用某个函数来清理动态指针,而不仅仅是使用
delete。在构造函数中我正在做thingPtr = LIB_CreateThing(...),而在析构函数中我正在做LIB_DestroyThing(thingPtr)。 -
@Tagglink
std::unique_ptr允许您为此类情况提供自定义删除器。
标签: c++11 vector destructor