make_shared 是否忽略显式说明符?
Does make_shared ignore explicit specifier?
考虑以下示例:
#include <iostream>
#include <memory>
struct A
{
explicit A(int x)
{
std::cout << x << std::endl;
}
};
void Foo(A ) {}
std::shared_ptr<A> Foo2(int x)
{
// why does this work?
return std::make_shared<A>(x);
}
int main()
{
A a(0);
Foo(a);
// Foo(1); does not compile
Foo2(2);
}
我有一个带有显式标记构造函数的 class A
,因此它不会从 int
隐式转换为 class A
。但是在对 std::make_shared
的调用中,我可以通过仅传递 int
来调用和创建此 class。为什么这是可能的,我的做法有问题吗?
这是预期的行为,因为 std::make_shared
performs direct-intialization,它也考虑了显式构造函数。
The object is constructed as if by the expression ::new (pv) T(std::forward<Args>(args)...)
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.
Foo(1);
不起作用,因为参数获取 copy-initialized,不会考虑显式构造函数。
考虑以下示例:
#include <iostream>
#include <memory>
struct A
{
explicit A(int x)
{
std::cout << x << std::endl;
}
};
void Foo(A ) {}
std::shared_ptr<A> Foo2(int x)
{
// why does this work?
return std::make_shared<A>(x);
}
int main()
{
A a(0);
Foo(a);
// Foo(1); does not compile
Foo2(2);
}
我有一个带有显式标记构造函数的 class A
,因此它不会从 int
隐式转换为 class A
。但是在对 std::make_shared
的调用中,我可以通过仅传递 int
来调用和创建此 class。为什么这是可能的,我的做法有问题吗?
这是预期的行为,因为 std::make_shared
performs direct-intialization,它也考虑了显式构造函数。
The object is constructed as if by the expression
::new (pv) T(std::forward<Args>(args)...)
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.
Foo(1);
不起作用,因为参数获取 copy-initialized,不会考虑显式构造函数。