【发布时间】:2014-02-10 21:44:53
【问题描述】:
Dictionary::Dictionary() {
ifstream infile;
infile.open("words");
string wread;
while(getline(infile,wread)){
wordset.insert(wread);
vector<string> st =Read::Trigrams(wread);
//Word w(wread,st) stack försvinner när vi lämnar metoden.
words[wread.length()].push_back(Word(wread,st)); //stack eller heap
}
infile.close();
}
这是一个类 Dictionary 的构造函数。 我想创建一个单词对象并将其添加到向量中。 我应该写吗 words[wread.length()].push_back(Word(wread,st)); 或者 字 w(wread,st); 单词[wread.length()].push_back(w); w 会被分配到栈中,当我们离开构造函数时它会被移除。
【问题讨论】:
-
没什么区别,都是在栈上分配的。
-
实际上你应该使用
emplace_back以提高性能和清晰度。 -
@HansPassant 标准实际上并没有具体说明,但实际上你是正确的。具有自动 存储持续时间的对象几乎总是在堆栈上分配。但是,只要生命周期仍然是自动的,实现可能会选择在堆上分配。
-
@Mgetz “具有自动存储持续时间的对象几乎总是在堆栈上分配” - 嗯,没有。那么类中声明的所有值对象呢?
标签: c++