2
std::map<std::string, std::shared_ptr<SomeClass>> map_string_to_object_pointer;


map_string_to_object_pointer["abcd"] = std::make_unique<SomeClass>();

The question is about assigning a unique_ptr to a shared_ptr. This is an existing code and hence just trying to understand if its a bad programming or assigning unique to shared_ptr implicitly convers the unique_ptr into shared? There is no compiler warning due to this.

infoclogged
  • 3,641
  • 5
  • 32
  • 53
  • Why shouldn't be? It's even safer than assigning regular pointer, though in this case it doesn't make sense to use `make_unique` instead of `make_shared`. – Dan M. Aug 16 '18 at 10:42
  • @lubgr thanks for the reference to the duplicate. That is what i was exactly looking for. – infoclogged Aug 16 '18 at 10:45

2 Answers2

3

Yes, this invokes corresponding assignment operator:

 template< class Y, class Deleter > 
 shared_ptr& operator=( std::unique_ptr<Y,Deleter>&& r );
user7860670
  • 35,849
  • 4
  • 58
  • 84
  • 2
    Only thing I would add is that you need to std::move a unique_ptr into a shared_ptr - as signified by the rvalue reference signature of the constructor. Reason why it works in the original posted code is because the call to make_unique is an rvalue – divinas Aug 16 '18 at 10:43
0

Such an overload exists for both the constructor and assignment (even std::auto_ptr is accepted 0_o.)

There is indeed only one bad programming practice: to do something without actually having an idea of what you're doing. Everything else is quite acceptable.

bipll
  • 11,747
  • 1
  • 18
  • 32
  • 1
    I don't think the random commentary in this answer adds anything to it. To the contrary. – Max Langhof Aug 16 '18 at 10:54
  • @MaxLanghof Excuse me? – bipll Aug 16 '18 at 13:56
  • I was letting you know that I find the second paragraph neither agreeable nor relevant to this question. – Max Langhof Aug 16 '18 at 14:16
  • And how exactly? The question was 'whether it is a bad programming' and I try to give the most detailed answer to that. – bipll Aug 16 '18 at 14:31
  • I would not interpret the question "is it a bad programming" to mean "is it bad practice" when the title specifically asks about "allowed". Regardless, the question is about existing code, so "it's not bad practice if [the author] understands what they are doing" is 1) not of use to the asker (who is not the author) and 2) frankly bad advice, because understanding something does not make it good practice. Just because I know what I'm doing with `GOTO`s does not justify using them (because the next programmer to work on that code might not). – Max Langhof Aug 16 '18 at 14:47