#1228 getting an element from a std::vector returns a reference

open
nobody
python (259)
5
2012-03-06
2012-03-06
No

When one wraps a std::vector using std_vector.i, getting an item by index returns a reference to the element in the vector instead of a copy.
This leads to dandling references if the vector is garbage collected.

For instance, in the following example

in the .i:
class X;
%template(XVector) std::vector<X>;

in the .py

def toto():
vector = XVector([X(0), X(1))
element = vector[0]
return element

myelement = toto()

myelement points to a freed element, thus its value is random.

This example can be found there : https://gist.github.com/1985700

The problem was raised on swig-user too:

http://thread.gmane.org/gmane.comp.programming.swig/18237
http://thread.gmane.org/gmane.comp.programming.swig/18444
http://thread.gmane.org/gmane.comp.programming.swig/18450

The first thread provides a workaround, using a typemap.

Discussion

    • summary: getting an element --> getting an element from a std::vector return a reference
     
    • summary: getting an element from a std::vector return a reference --> getting an element from a std::vector returns a reference