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) {
{
std::shared_ptr<std::string> s1(new std::string("good"));
std::shared_ptr<std::string> s2(s1.get());
std::cerr << s2.use_count() << std::endl;
}
{
std::shared_ptr<int> i1(new int(1));
std::shared_ptr<int> i2(i1.get());
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++?