考虑这个程序:
#include <memory>
struct T {
T() {}
};
void do_something(std::shared_ptr<T> ptr) {
// Do something with ptr; might or might not leave
// other copies of ptr in other variables of the
// program
}
int main() {
std::shared_ptr<T> ptr = std::make_shared();
do_something(ptr);
// ptr might or might not be the only owner
ptr = std::make_shared();
return 0;
}
当 make_shared
第二次执行,ptr
可能有也可能有其他共享所有者,这取决于运行时在 do_something
中发生的情况.如果没有其他人,ptr
当或多或少同时分配和构造同一时间的新对象时,破坏并释放其先前拥有的对象。有没有办法避免分配和释放,并使用相同的区域来构造新对象? (这里的目标是优化对分配器的两次调用)
当然我接受新的T
object 将在旧的对象被破坏之后构造,而在上面的代码中恰恰相反。所以我想要类似 ptr.replace<U>(args)
的东西它执行以下操作:它递减 ptr
的引用计数;如果计数变为零,则没有其他弱引用和 U
是 ptr
内容的最派生类型, 它会破坏拥有的对象并构造一个带有参数 args
的新对象在同一内存区域中,避免调用内存分配器。否则它的行为类似于 ptr = std::make_shared<U>(args)
.
有没有办法用当前的标准库进行这种优化?
最佳答案
没有计算共享对象的 weak_ptr
数量的机制。您只能查询强计数(通过 shared_ptr::use_count
)。请注意,在多线程环境中,这可以是一个近似计数(即使用 memory_order_relaxed
加载)。
您确定这是性能瓶颈吗?
关于c++ - 替换共享指针的内容时优化对分配器的调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55513474/