这很可能是微不足道的,我以某种方式混淆了结构分配和指针,我为此道歉。我已经阅读了类似问题的答案,但没有帮助。代码一如既往地更加复杂,这是从 3000 多行代码减少到要点。
我期望的输出是
prep 1
main 1
相反,我得到
prep 1
main 0
这是代码:
#include <iostream>
#include <vector>
using namespace std;
struct Entry
{
vector<int> list;
};
struct Registry
{
vector<Entry> entries;
void prep()
{
Entry* entry = new Entry();
entries.push_back(*entry);
entry->list.push_back(0);
cout << "prep " << entry->list.size() << "\n";
}
};
int main()
{
Registry registry;
registry.prep();
cout << "main " << registry.entries[0].list.size() << "\n";
return 1;
}
你不在你的指针中存储指针,vector<Entry>
所以你不应该使用new
. 而是添加一个Entry
使用emplace_back
.
C++17 方法:
void prep()
{
Entry& entry = entries.emplace_back(); // returns a ref the added element
entry.list.push_back(0);
cout << "prep " << entry.list.size() << "\n";
}
在 C++17 之前:
void prep()
{
entries.emplace_back(); // does NOT return a ref the added element
Entry& entry = entries.back(); // obtain a ref to the added element
entry.list.push_back(0);
cout << "prep " << entry.list.size() << "\n";
}
如果您确实想Entry
在将其添加到 之前创建和操作它entries
,您也可以这样做,然后将std::move
其添加到entries
.
void prep()
{
Entry entry;
entry.list.push_back(0);
cout << "prep " << entry.list.size() << "\n";
entries.push_back(std::move(entry)); // moving is a lot cheaper than copying
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句