From my understanding, when s
returns a vector and is assigned vm
, this is done as a copy (by value). Therefore, if s
out of scope and calls it a destructor, vm
has its own copy, and its structure is not affected.
Simple pointers ( T*
) should not have the std::vector
copy constructor or assignment operator (although you can use the smart pointer class that will copy). Since pointers indicate (“pointed”) are not copied, the copy operation is a shallow copy. While operations with sv
will not affect vm
(and vice versa), everything that affects pointed access from one will affect the other, since they are the same.
If you were to save a properly implemented smart pointer to sv
, not MyStorageClass*
, the standard std::vector
copy operations could make deep copies so that the contents of sv
can be changed without affecting the contents of vm
any way (and vice versa ) Copy pointer copy operations will use copy operations of the specified class to duplicate a pointed object. As a result, only one copy pointer will be pointed at each sharp object.
Alternatively (as mentioned in other publications), you can use a smart pointer that allows shared ownership and allows you to manage specified objects by eliminating the delete
call in ~storage
.
However, transmission by value is inefficient.
However, in some cases this is correct, especially if the mutation of one instance of the container should not affect another (the case you mentioned), in which case you cannot leave without a copy. Correct trump cards are effective. Generally speaking, you can use the copy-replace idiom to reduce inefficiencies due to the creation of time series. As far as I know, most STL implementations do not use copy-swap for std::vector
. Copy-on-write , which will only copy when the vector changes, can also help. Threading complicates copy-on-write and can lead to inefficiencies.
Now vm
contains the address v
.
vm
does not contain an address. Although links may use pointers under the hood (they may also not be, may not even require additional storage, in accordance with § 8.3.3-3 C ++ 03), at the language level, links are not pointers. Note that you can have null pointers, but not null references. A more accurate instruction is that vm
smoothed to v
( vm
and v
refer to the same object), so operations on v
will affect vm
(and vice versa).