【发布时间】:2020-05-02 02:29:07
【问题描述】:
我经常面临这样的论点,即通过接受const std::shared_ptr<T>& 可以避免引用计数增加:
void foo(std::shared_ptr<const int> p);
void foo2(const std::shared_ptr<const int>& p);
int main(){
std::shared_ptr<const int> a = std::make_shared<int>(3);
foo(a); // calling this function always does reference counting (atomic locks...)
foo2(a); // calling this function elides reference counting
std::shared_ptr<int> b = std::make_shared<int>(3);;
foo2(b); // what happens here? since there is a cast involved creating a temporary ... (NRVO??)
}
但我假设在调用foo2(b) 时不会省略引用计数?但是,编译器或标准实现是否可以以某种方式忽略引用计数。如果调用 foo2(std::move(b)) 会不会更好,以实现这种省略?
【问题讨论】:
-
如果函数没有将智能指针存储在别处供以后使用,它应该采用普通引用或指针,而不是智能指针。
-
为了说明@MaximEgorushkin 的观点,请考虑:
void foo3(const int * p); void foo4(const int * const & p); -
没错,但这不是问题。
-
原子指令不是锁,这正是它们的重点。 (这并不是说你试图避免它们是错误的。)
标签: c++ c++11 c++17 shared-ptr c++20