For example:
std::unique_ptr<int> int_ptr = new int(10); // error: conversion from ‘int*’ to non-scalar type ‘std::unique_ptr’ requested
std::unique_ptr<int> pointer(new int(10)); // this work fine
CodePudding user response:
Both of them are initialization, but not assignment. The 1st one is copy initialization, the 2nd one is direct initialization. The constructor of std::unique_ptr
taking raw pointer is marked as explicit
, it could be used in direct initialization but not copy initialization.
explicit unique_ptr( pointer p ) noexcept;
Direct-initialization is more permissive than copy-initialization: copy-initialization only considers non-explicit constructors and non-explicit user-defined conversion functions, while direct-initialization considers all constructors and all user-defined conversion functions.