简体   繁体   中英

Memory management with std::vector and boost::thread

Suppose I have the following code

class simple_class
{
public:
    simple_class() { }

    void start()
    {
        boost::thread simple_thread(&simple_class::expand,this);
    }

    void expand()
    {
        while(1)
        {
            this->private_vector.push_back((int)1);
        }
    }
private:
    std::vector<int> private_vector;
};

int main()
{
    simple_class* obj1 = new simple_class();
    simple_class* obj2 = new simple_class();
    obj1->start();
    obj2->start();
    while(1) {}
}

Obviously this program will run out of memory at some point and should throw a std::bad_alloc . But my question is the following:

  1. Is there a case that private_vector of obj1 will be over-written by private_vector of obj2 before that happen? Is there a way to be protected from this?
  2. If i enforce the private_vector in the class to be aligned in memory (like Eigen does with its matrices) when we define EIGEN_MAKE_ALIGNED_NEW_OPERATOR will this change things wrt to question 1?

I'm not normally one to answer questions, but I am almost 100% sure the answer to this is:

  1. "No." You're using the new operator and an STL object. The biggest thing you have to worry about, as you pointed out, is quickly running out of memory.

  2. No again. I don't know anything about Eigen matrices, but memory alignment will be determined by the OS and the compiler, not by the language.

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