سؤال

I have a question regarding copying pointers in the stl library. Say I define:

struct A{ int x; }

std::map<int, const A*> map1;

I then populate map1 using memory from the heap using malloc for the pointer to A.

Then I do

std::map<int, const A*> map2 = map1;

For each pointer of struct A in map2, does std::map do a shallow copy of the pointers, or assign new memory from the heap for each of the pointers?

Cheers

Shanker

هل كانت مفيدة؟

المحلول

It will copy just the pointers. That means that a shallow copy will be made as opposed to a deep copy. You can easily check the actual behavior by using a simple test program:

int main() {
    std::map<int, int*> map1;        
    map1[0] = new int(10);

    std::map<int, int*> map2 = map1;
    *(map2[0]) = 20;

    // this must print 20 if a shallow copy is used
    std::cout << *(map1[0]) << std::endl;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top