简体   繁体   中英

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();
}

This ia constructor for a class Dictionary. I want to create a word object and add it to vector. Should i write words[wread.length()].push_back(Word(wread,st)); or Word w(wread,st); words[wread.length()].push_back(w); w will be allocated on the stack and it will be removed when we leave the constructor.

In C++11 the first form push_back(Word()); is going to be more efficient, iff Word has a move constructor. The second form will make a copy regardless.

Functionality wise, both are equivalent. The second pollutes the scope, the first doesn't. The first is more likely to be optimized efficiently, the second isn't.

Unless restricted by backward compatibility you should use vector::emplace_back and either pass a value of T or the parameters of one of its constructors.

The "proper" way to do this is to use emplace_back , which will construct the Word in-place, removing even the move.

Note that emplace_back takes the same arguments as the object's constructor.

Neither of the forms you mentioned will allocate on the heap. To allocate on the heap you will generally use the new keyword

new Word()

There are other ways to allocate on the heap including std::make_shared . But none are used in your sample. Using simply Word() will allocate on the stack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM