Error defining std :: shared_ptr with new operator

I am trying to define an operator std::shared_ptrwith an operator newas follows:

#include <memory>

struct A {
};

int main() {

  std::shared_ptr<A> ptr = new A();

  return 0;
}

but I got the following compile time error:

main.cpp: In the function 'int main ()':

main.cpp: 8:30: error: conversion from "A *" to the non-scalar type "std :: shared_ptr" requested by std :: shared_ptr ptr = new A ();

In any case, the following definitely works:

      std::shared_ptr<A> ptr{new A()};

Do any of you know why this is happening?

+4
source share
2 answers

tl; dr: this is a consequence of the corresponding constructor explicit.

=, -. ++ - shared_ptr , shared_ptr, .

, "" shared_ptr ( ). , , , .

- std::shared_ptr<A> ptr = new A()? . , , , ++ .

+6

2- , .

A* a = new A();
std::shared_ptr<A> ptr = a;

, , .

A* a = new A();
//.....
std::shared_ptr<A> ptr = a;
//.....
std::shared_ptr<A> ptr2 = a; //second ptr holding a... UB

2 , , .

"" , ++ ​​.

, "" .

std::shared_ptr<A> ptr{ new A() };

.

auto ptr = std::make_shared<A>();
+3

Source: https://habr.com/ru/post/1657266/


All Articles