简体   繁体   中英

Strange issue with the constructor called by vector<T>

vector< MyObject<MyType> > ObjectList(100, MyObject<MyType>(param1));

MyObject internally creates a member called 'storage' which is an array of MyType using the on the heap.

But use the line of code above, every item in ObjectList has 'storage' pointing to the same memory location (essentially sharing the storage).

This issue does not occur when I allocate the list on the stack manually using

MyObject<MyType> ObjectList[100] = { MyObject<MyType>(param1), 
                                     MyObject<MyType>(param1), ...};

Every storage has its own memory location when I declare MyObject with the above line.

But use the line of code above, every item in ObjectList has 'storage' pointing to the same memory location (essentially sharing the storage).

If you've written proper copy-constructor for MyObject (and MyType if it also contains pointers), then that would not happen, because ObjectList is initialized with the copies of what you pass.

By "proper" I meant copy-ctor which does deep-copy , instead of shallow-copy !

See this:

What is the difference between a deep copy and a shallow copy?

To expand on the above answers, need to break your line of code:

vector< MyObject<MyType> > ObjectList(100, MyObject<MyType>(param1))

into its two components:

MyObject<MyType> myObject(param1)
vector< MyObject<MyType> > ObjectList(100, myObject)

As you can see, you are creating 'myObject' once, and then calling its copy constructor 100x times (rather than creating 100x MyObjects).

Judging by what you are expecting you have not created a custom copy constructor - so are getting (as others have mentioned) default 'shallow copy' behaviour.

I would also recommend to not use naked pointers/heap allocation (eg MyType* t = new MyType[param1]) new inside of MyObject, rather implement storage with another vector, which already supports the copy mechanisms your probably expect.

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