Understanding a compilation error

Hi,

I was getting confused with the usage of "new" in case of shared_ptr.

(1)shared_ptr<int>sharedPointer(new int (7));
This one works fine.

(2) shared_ptr<int>sharedPointer;
sharedPointer = new int (7);

As of my current understanding in both the scenarios new is returning a pointer of int type .
In the 2nd Line ,its throwing an error of no match for operator= (operand types are std::shared_ptr<int>' and int * );

Since "new" in this case is returning an int * why this error when assignment operator comes to picture ?

Can anybody explain ,the difference in both the cases ?

Thanks in advance.
Nihar

Actually in modern C++ you should not use new at all.
The proper way is to use make_shared or make_unique.

So your code should be more like:
shared_ptr<int> sharedPointer = make_shared<int>(7);

https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rr-make_shared
First, prefer std::make_shared to explicit use of new. See http://www.cplusplus.com/reference/memory/make_shared/

A constructor of std::shared_ptr
http://www.cplusplus.com/reference/memory/shared_ptr/shared_ptr/
does construct from pointer (3) of element_type.

There are assignment operators
http://www.cplusplus.com/reference/memory/shared_ptr/operator=/
accept shared_ptr, auto_ptr and unique_ptr, but no raw element_type pointer.

There is shared_ptr::reset() to change the stored pointer:
http://www.cplusplus.com/reference/memory/shared_ptr/reset/
Last edited on
> the difference in both the cases ?

Case (1) std::shared_ptr<int> sharedPointer( new int (7) );
Direct initialisation: http://en.cppreference.com/w/cpp/language/direct_initialization
ergo constructor http://en.cppreference.com/w/cpp/memory/shared_ptr/shared_ptr
Fine, resolves to constructor (3)

Case (2) shared_ptr<int>sharedPointer; sharedPointer = new int (7);
Default construction followed by assignment. ergo, looks for an overloaded assignment operator. http://en.cppreference.com/w/cpp/memory/shared_ptr/operator%3D
Error, no overloaded assignment operator which can accept a raw pointer as the operand on the rhs.

Note that the constructor that was used in case (1) is not a converting constructor;
Converting constructor: http://en.cppreference.com/w/cpp/language/converting_constructor
(So can't implicitly convert the raw pointer to a shared pointer and then assign the result of the conversion.)
Last edited on
Registered users can post here. Sign in or register to post.