-3
class SmartPointer
{
int* _data;
public:
    explicit SmartPointer(int* data) : _data(data)
    {}
};

This code compiles:

SmartPointer p(nullptr);

But this one doesn't:

SmartPointer p = nullptr; // error C2440: 'initializing': cannot convert from 'nullptr' to 'SmartPointer'

Aren't these two ways of calling the copy constructor equivalent?

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
embedc
  • 1,485
  • 1
  • 6
  • 20

1 Answers1

1

The issue has nothing to do with calling copy constructor; I think you meant two ways of initialization.

The 1st one is direct initialization, which considers all the appropriate constructors, including explicit constructors. The 2nd one is copy initialization, which only considers non-explicit ones.

Copy-initialization is less permissive than direct-initialization: explicit constructors are not converting constructors and are not considered for copy-initialization.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405