fork download
  1. #include <iostream>
  2. #include <memory>
  3.  
  4. class Base {};
  5.  
  6. class Derived : public Base {};
  7.  
  8. void f(std::shared_ptr<Base>& x)
  9. {
  10. std::cout << "in function expecting const shared_ptr<Base>& - Use count: " << x.use_count() << std::endl;
  11. }
  12.  
  13. int main(int argc, char const *argv[])
  14. {
  15. std::cout << "Base class" << std::endl;
  16. auto a = std::make_shared<Base>();
  17. std::cout << "Created shared_ptr: Initial use count: " << a.use_count() << std::endl;
  18. f(a);
  19.  
  20. std::cout << "------------------\nChild class" << std::endl;
  21. auto b = std::make_shared<Derived>();
  22. std::cout << "Created shared_ptr. Initial use count: " << b.use_count() << std::endl;
  23. f(b);
  24.  
  25. return 0;
  26. }
Compilation error #stdin compilation error #stdout 0s 15240KB
stdin
Standard input is empty
compilation info
prog.cpp: In function ‘int main(int, const char**)’:
prog.cpp:23:8: error: invalid initialization of non-const reference of type ‘std::shared_ptr<Base>&’ from an rvalue of type ‘std::shared_ptr<Base>’
     f(b);
        ^
In file included from /usr/include/c++/6/memory:82:0,
                 from prog.cpp:2:
/usr/include/c++/6/bits/shared_ptr.h:221:2: note:   after user-defined conversion: std::shared_ptr<_Tp>::shared_ptr(const std::shared_ptr<_Tp1>&) [with _Tp1 = Derived; <template-parameter-2-2> = void; _Tp = Base]
  shared_ptr(const shared_ptr<_Tp1>& __r) noexcept
  ^~~~~~~~~~
prog.cpp:8:6: note:   initializing argument 1 of ‘void f(std::shared_ptr<Base>&)’
 void f(std::shared_ptr<Base>& x)
      ^
stdout
Standard output is empty