你对语言的理解有些偏离。这是您的代码注释:
vector<SomeClass> objs;
SomeClass obj; // create a new obj with a new name
objs.push_back(obj);
while (someConditionIsTrue()){
use(&obj);
obj = new SomeClass(); // create a new obj with an existing name
objs.pushback(obj)
}
这是实际发生的事情
// create an object called "objs" which is a std::vector header, on the stack.
vector<SomeClass> objs;
// create an instace of "SomeClass" on the stack, call it obj.
SomeClass obj;
// allocate storage in the heap for some number of SomeClass instances to
// act as the storage for "objs", and assign them to it's "m_data" member.
// default construct the first one,
// then call it's copy constructor with the stack instance of "Obj" to
// copy the values/data into the first entry of the heap allocation of objs.
objs.push_back(obj);
while (someConditionIsTrue()){
// pass a pointer to the stack-allocated instance of obj.
use(&obj);
// create a new instance of "SomeClass" on the heap,
// default/zero construct it,
// return the pointer to this heap allocation and pass it
// to obj.operator=(const SomeClass*) to copy the data into
// the stack space allocated for "obj".
obj = new SomeClass(); // create a new obj with an existing name
// leak the pointer to the previous heap allocation by not storing it.
// increase the size of the heap allocation backing objs and then
// default construct the first SomeClass instance in the new space,
// then copy our freshly copy-initialized stack instance back into it.
objs.pushback(obj)
}
您可以通过多种其他方式编写此代码,但这似乎是最明智的方式。
std::vector<SomeClass> objs;
while (someConditionIsTrue()) {
objs.resize(objs.size() + 1); // grow me a new element.
use(&objs.back());
}
或者让“使用”作为参考。
void use(SomeClass& obj);
//...
use(objs.back());
如果你真的想要一个本地对象来尝试输入。
while (someConditionIsTrue()) {
objs.resize(objs.size() + 1);
// the compiler will either optimize this out entirely,
// or use a pointer under the hood.
SomeClass& obj = objs.back();
use(&obj); // take the address of the object obj references.
}
另外,请注意“resize()”可能会变得昂贵。您可能希望预先执行此操作:
objs.reserve(1024); // or something you know is likely to cover most use cases.
如果你真的,真的必须使用指针。
SomeClass* obj = nullptr;
while (someConditionIsTrue()) {
objs.resize(objs.size() + 1);
obj = &objs.back();
use(obj);
}
而不是“objs.resize()”,您可以使用带有 ctor 的placement-new:
objs.emplace_back(SomeClass());
其他人建议您使用
obj = Someclass();
但请注意,这是复制对象的默认构造的堆栈副本。
{
SomeClass tempObj;
obj.operator=(std::move(tempObj));
}
我不认为那是你真正想要做的。它比仅仅拥有这样的堆栈本地副本更昂贵:
while (someCondition()) {
SomeClass stackCopy;
...
}
编译器足够聪明,不会在每个循环中放弃堆栈空间。它将做的是一个名为“Placement new”的东西来重新调用同一个对象上的构造函数:
SomeClass obj;
while (someCondition()) {
new (&obj) SomeClass(); // Call SomeClass() ctor on the memory at &obj
...
}
但是 - 这基本上是编译器实现我之前的代码示例的方式。