What is the correct initialisation of a smart pointer?

std::unique_ptr<Class> ptr(std::make_unique<Class>());


std::unique_ptr<Class> ptr = std::make_unique<Class>();

Is there an implicit copy with the second usage?

  • Shouldn't that be auto ptr = std::make_unique<Class>();? DRY. – Martin Ba Mar 22 '16 at 23:08

The two are equivalent.

The second would (officially) require an implicit copy if (and only if) the type of the initializer differed from the type of the object being initialized. In reality, even in that case most compilers can normally generate code that elides the copy.

  • Actually, I'm pretty sure that C++ requires that the copy be elided. The initialization of a variable by T t = T(); is required to have a valid and accessible copy constructor, but the standard requires that no copy constructor is called. – Nicol Bolas Mar 22 '16 at 3:11
  • 2
    @NicolBolas: No--for T t = T();: "If the initialization is direct-initialization, or if it is copy-initialization where the cv-unqualified version of the source type is the same class as, or a derived class of, the class of the destination, constructors are considered. [...overloads are resolved, then] The constructor so selected is called to initialize the object, with the initializer expression or expression-list as its argument(s)." This doesn't require an available copy ctor. – Jerry Coffin Mar 22 '16 at 4:20
  • If conversion is needed, a constructor is selected, and: "In certain cases, an implementation is permitted to eliminate the copying inherent in this direct-initialization by constructing the intermediate result directly into the object being initialized; see 12.2, 12.8." §12.8 says: "when a temporary class object that has not been bound to a reference (12.2) would be copied/moved to a class object with the same cv-unqualified type, the copy/move operation can be omitted by constructing the temporary object directly into the target of the omitted copy/move". If that's not met, copy is required. – Jerry Coffin Mar 22 '16 at 4:33
  • Well, I would use type inference there... – Deduplicator Mar 22 '16 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.