Segment error for a simple case of building std :: shared_ptr

From cppreference, I find out that there is a constructor for std::shared_ptr:

template< class Y > explicit shared_ptr( Y* ptr );

And I tried the code snippet as follows:

#include <string>
#include <memory>
#include <iostream>

int main(void) {
  /// block 1
  {
    std::shared_ptr<std::string> s1(new std::string("good"));
    std::shared_ptr<std::string> s2(s1.get()); /// s2
    std::cerr << s2.use_count() << std::endl;
  }
  /// block 2
  {
    std::shared_ptr<int> i1(new int(1));
    std::shared_ptr<int> i2(i1.get());  ///  i2
    std::cerr << i2.use_count() << std::endl;
  }
  return 0;
}

It causes a segment error for block 1, but not for block 2, but both use_countare equal to 1. The difference that I can think of is that it intis a primitive type and is std::stringcontrolled by a allocator.

I read bits/shared_ptr.hof gcc-4.9and found that there is post-help for this constructor:

use_count() == 1 && get() == __p

Question 1:

Should std::shared_ptrNOT be constructed with a raw pointer referenced by another smart pointer? In this sense, the preferred way to use this constructor is as follows:

std::shared_ptr<T>(new T(...));

Question 2:

, libstdc++?

+4
2

std::shared_ptr.

std::shared_ptr . std::shared_ptr , , .

.

std::shared_ptr, , (, , std::make_shared), / . , ( ), std::shared_ptr .

, , , , int , int, .

+8

undefined, , cppreference std:: shared_ptr , ( )

shared_ptr raw- shared_ptr, undefined , , std:: enable_shared_from_this ( , raw pointer ).

shared_ptr , , , . , undefined, ++ 3.7.4.2 Deallocation, :

, - , (4.10), , , , . undefined. [...]

. cppreference :

 std::cout << "constructor with object\n";
 std::shared_ptr<Foo> sh2(new Foo);
 std::shared_ptr<Foo> sh3(sh2);     // <- using copy construction

shared_ptr std:: make_shared, :

, , f (std:: shared_ptr (new int (42)), g()), , g , g() int (42) shared_ptr. f (std:: make_shared (42), g()), .

+3

All Articles