0

The following code is a minimal example of this strange error.
The constructor of bar takes a pointer to the base class BaseFoo as argument.
When I tried to make a list of three BaseFoo pointers and create a Bar object for each of them, I get segmentation error.
However, if I only make two BaseFoo I seldom get any error.
Can someone explain why?

import cppyy

cppyy.cppdef(r'''
#include <memory>

using namespace std;

struct BaseFoo {
    BaseFoo() = default;

    virtual ~BaseFoo() {}
};

struct Foo: public BaseFoo {
    Foo() {}

    static shared_ptr<Foo> make() { return make_shared<Foo>(); }

    virtual ~Foo() {}
};

class Bar {
private:
    const shared_ptr<BaseFoo> foo;
public:
    explicit Bar(const shared_ptr<BaseFoo> &foo): foo(foo) {}

    static shared_ptr<Bar> make(const shared_ptr<BaseFoo> &param) {
        return make_shared<Bar>(param);
    }
};
''')

from cppyy.gbl import Foo, Bar


def get_params():
    params = cppyy.gbl.std.vector['shared_ptr<BaseFoo>']([
        Foo.make(), Foo.make(), Foo.make()
    ])
#     params = cppyy.gbl.std.vector['shared_ptr<BaseFoo>']([
#         Foo.make(), Foo.make()
#     ])
    
    return [p for p in params]

for p in get_params():
    Bar.make(p)
Max Wong
  • 694
  • 10
  • 18

0 Answers0