I have a struct in C++ like this:
struct MyStruct
{
someType v1;
someType2 v2;
someType3 v3;
someType4 f1();
std::vector<someType> myVector;
} ;
It will be very often used in forms like this:
//some process... after which a std::vector<someType> vec1 is generated
MyStruct myStruct;
myStruct.myVector = vec1;
Since vec1 is relative large. I want to know if it costs much time by doing the assignment myStruct.myVector = vec1;
Should I use a pointer to myVector in MyStruct to make it faster? And how?
Since vec1 is relative large. I want to know if it costs much time by doing the assignment
It costs time in linear proportion to the size of the vector.
Should I use a pointer to vec in MyStruct to make it faster?
Given the problem that you've described, no I would not suggest you use a pointer unless you've left out relevant details.
You could move assign the vector (since C++11), or swap it (prior to C++11). But that assumes that you don't need vec1
for anything else.
There is a fundamental difference between std::vector<someType> myVector
and std::vector<someType*> myVector
. The non-pointer version actually owns and stores the data. This means once the assignment is made changes to the original variable will not result in changes to your vector (deep copy).
In the pointer version, storage is external to the vector. This means that changes to the original will result in changes to your vector (shallow copy). The is another knock on effect as well.
Since storage is external to your vector, it is your responsibility to ensure that the original sticks around for longer than your vector. Otherwise bad things will happen. This can be mitigated with a std::shared_ptr
but you are still aliasing the same memory.
So the question you need to ask is whether you require a shallow copy or a deep copy.
Also std::move
will only save you a copy if data is stored external to the struct
(like an stl-container) otherwise you will need to move a std::unique_ptr<someType>
to save the copy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With