![](/img/trans.png)
[英]Where does a stack object inside a heap allocated object gets allocated in c++?
[英]Object allocated on stack or heap c++
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的构造函数。 我想创建一个单词对象并将其添加到矢量。 我应该写单词[wread.length()]。push_back(Word(wread,st)); 或Word W(wread,st); 。字[wread.length()]的push_back(W); w将在堆栈上分配,当我们离开构造函数时它将被删除。
在C ++ 11中,第一个形式是push_back(Word());
如果Word
有一个移动构造函数,那将会更有效率。 第二种形式无论如何都会复制。
功能明智,两者都是等价的。 第二个污染范围,第一个没有。 第一种更有可能被有效地优化,第二种不是。
除非受向后兼容性限制,否则应使用vector::emplace_back
并传递T
值或其构造函数之一的参数。
执行此操作的“正确”方法是使用emplace_back
,它将就地构造Word,甚至移除移动。
请注意, emplace_back
采用与对象构造函数相同的参数。
您提到的两种表单都不会在堆上分配。 要在堆上分配, 通常会使用new
关键字
new Word()
还有其他方法可以在堆上进行分配,包括std::make_shared
。 但是您的样本中没有使用任何内容。 使用简单的Word()
将在堆栈上分配
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.