std::shared_ptr 模板化与非模板化 copy/move 构造函数

std::shared_ptr templated vs. non-templated copy/move constructors

This page shows that std::shared_ptr has a templated and a non-templated version of copy/move constructors ((9) and (10) on the page). Similarly, it also has two versions of copy/move assignment operator (see here).

为什么我们需要非模板版本?单靠模板版本还不够吗?

模板化版本不是复制构造函数。根据标准 §12.8[class.copy]/2 我们有:

A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

同样,根据§12.8[class.copy]/17:

,模板化版本也不是复制赋值运算符

A user-declared copy assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X, X&, const X&, volatile X& or const volatile X&.

移动构造函数也是如此(在 §12.8[class.copy]/3):

A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).

并移动赋值运算符,在 §12.8[class.copy]/19:

A user-declared move assignment operator X::operator= is a non-static non-template member function of class X with exactly one parameter of type X&&, const X&&, volatile X&&, or const volatile X&&.