Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
weak_ptr and Circle_reference
Language:
Ada
Assembly
Bash
C#
C++ (gcc)
C++ (clang)
C++ (vc++)
C (gcc)
C (clang)
C (vc)
Client Side
Clojure
Common Lisp
D
Elixir
Erlang
F#
Fortran
Go
Haskell
Java
Javascript
Kotlin
Lua
MySql
Node.js
Ocaml
Octave
Objective-C
Oracle
Pascal
Perl
Php
PostgreSQL
Prolog
Python
Python 3
R
Rust
Ruby
Scala
Scheme
Sql Server
Swift
Tcl
Visual Basic
Layout:
Vertical
Horizontal
#include <iostream> #include <memory> using namespace std; struct A; struct B; struct A{ weak_ptr<B> b; A (){ cout<<"A ctor"<<endl; } ~A(){ cout<<"A dtor"<<endl; } void SayHello(){ cout << "Hello I am A" << endl; } }; struct B{ weak_ptr<A> a; B (){ cout<<"B ctor"<<endl; } ~B(){ cout<<"B dtor"<<endl; } void CallA(){ auto sA = a.lock(); sA->SayHello(); } }; int main() { weak_ptr<A> wA; weak_ptr<B> wB; { shared_ptr<A> sA(new A()); shared_ptr<B> sB(new B()); sA->b = sB; sB->a = sA; wA = sA; wB = sB; sB->CallA(); cout << wA.use_count() << endl; // 1 cout << wB.use_count() << endl; // 1 } cout << wA.use_count() << endl; // 0 cout << wB.use_count() << endl; // 0 return 0; }
g++
Show compiler warnings
[
+
] Compiler args
[
+
]
Show input
Compilation time: 0.53 sec, absolute running time: 0.08 sec, cpu time: 0.02 sec, memory peak: 3 Mb, absolute service time: 0,61 sec
edit mode
|
history
|
discussion
A ctor B ctor Hello I am A 1 1 B dtor A dtor 0 0