【发布时间】:2021-11-28 07:05:55
【问题描述】:
在下面的代码中,为什么对bar(std::shared_ptr<B>)的调用是模棱两可的,而bar(std::shared_ptr<A>)却不是?
foo 的目的是区别对待 const 和非 const 指针。除了将呼叫站点更改为 bar(std::dynamic_pointer_cast<A>(b)) 之外,我可以通过其他任何方式来消除歧义吗?
#include <memory>
struct A {};
struct B : A {};
void foo(std::shared_ptr<const A>) { }
void foo(std::shared_ptr<A>) { }
void bar(const A &) { }
void bar(A &) { }
int main() {
A a;
bar(a); // ok
B b;
bar(b); // ok
auto ap = std::make_shared<A>();
foo(ap); // ok
auto bp = std::make_shared<B>();
foo(bp); // ambiguous
return 0;
}
【问题讨论】:
-
A
void foo(std::shared_ptr<A>)将共享 所有权 传递给 foo 例程。如果意图是通过共享所有权,那么这是正确的做法。如果传递所有权不是意图,那么参数应该是A或A*或A const*或A&或A const&。