Skip to content

Commit 56bfadd

Browse files
committed
Archiving godbolt code.
1 parent 65c7096 commit 56bfadd

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// https://godbolt.org/z/sdhTqY
2+
3+
#include <iostream>
4+
#include <memory>
5+
6+
#define DUMP(expr) #expr " = " << (expr)
7+
8+
struct base {
9+
base() : base_id{100} {}
10+
virtual ~base() = default;
11+
virtual int const id() { return base_id; }
12+
int base_id;
13+
};
14+
struct monkeywrench {
15+
virtual int const monkey_id() { return 150; }
16+
virtual ~monkeywrench() = default;
17+
};
18+
struct drvd : monkeywrench, base {
19+
int const id() override { return 2 * base_id; }
20+
};
21+
22+
void drvd_void_base() {
23+
std::cout << "hello drvd_void_base" << std::endl;
24+
25+
// pybind11-wrapped C++ function returns shared_ptr<base> up-cast from drvd.
26+
std::shared_ptr<base> shared_drvd_uc(new drvd);
27+
std::cout << "have shared_drvd_uc" << std::endl;
28+
#if 0
29+
std::cout << "dynamic_pointer_cast<drvd>" << std::endl;
30+
std::shared_ptr<drvd> shared_drvd_dc = std::dynamic_pointer_cast<drvd>(shared_drvd_uc);
31+
#elif 1
32+
std::cout << "dynamic_pointer_cast<void> + static_pointer_cast<drvd>" << std::endl;
33+
std::shared_ptr<void> ivp = std::dynamic_pointer_cast<void>(shared_drvd_uc);
34+
std::cout << "have ivp" << std::endl;
35+
std::shared_ptr<drvd> shared_drvd_dc = std::static_pointer_cast<drvd>(ivp); // Is this well-defined?
36+
#else
37+
std::cout << "pybind11 <=2.6 behavior" << std::endl;
38+
// intermediate void pointer.
39+
const void *ivp = &shared_drvd_uc;
40+
std::cout << "have ivp" << std::endl;
41+
// intermediate shared_ptr<drvd> pointer.
42+
const std::shared_ptr<drvd> *isdp = (const std::shared_ptr<drvd>*) ivp; // ROOT CAUSE FOR SEGFAULT BELOW
43+
std::cout << "have isdp" << std::endl;
44+
std::shared_ptr<drvd> shared_drvd_dc = *isdp;
45+
#endif
46+
std::cout << "have shared_drvd_dc" << std::endl;
47+
std::cout << DUMP(shared_drvd_dc.use_count()) << std::endl;
48+
std::cout << DUMP(shared_drvd_dc->id()) << std::endl; // SEGFAULT HERE
49+
}
50+
51+
int main() {
52+
std::cout << "hello main" << std::endl;
53+
drvd_void_base();
54+
return 0;
55+
}

0 commit comments

Comments
 (0)