贡献指针shared_ptr是一种智能化指针。
其在传入函数中时如果使用shared_ptr类型,会导致进行内存拷贝,在多次运行时将大量延长传值时间。例程如下:
引用头文件
#include <stdio.h>
#include <iostream>
#include <memory>
#include "self_timer.h"
测试函数分别传入三种不同类型的共享指针和const &(不需要拷贝内存的)
void ShardPtrFunction(std::shared_ptr<std::string> first,
std::shared_ptr<std::string> second) {
// nothing to do
}
void ConstFunction(const std::string& first, const std::string& second) {
// nothing to do
}
void ConstShardPtrFunction(const std::shared_ptr<std::string>& first,
const std::shared_ptr<std::string>& second) {
// nothing to do
}
测试主程序,分别对三种方式的耗时进行统计。
int main(int argc, char* argv[]) {
int i = 0;
const int max_iters = 10000000;
std::shared_ptr<std::string> first = std::make_shared<std::string>(
"fhjkdsgfueawifbgjhzshjfzhjdgtusvbhjzgfjkzgj"
"hbzdszfzsdgdzsgsrjgbzjsh"),
second = std::make_shared<std::string>(
"fhjkdsgfueawifbgjhzshjfzhjdgtusvbhjzgfjkzgj"
"hbzdszfzsdgdzsgsrjgbzjsh");
{
long start_time = GetCurrentTimeInMilliSec();
while (i < max_iters) {
ShardPtrFunction(first, second);
++i;
}
long end_ptr_time = GetCurrentTimeInMilliSec();
std::cout << "time in shard_ptr: " << end_ptr_time - start_time
<< std::endl;
}
{
long start_time = GetCurrentTimeInMilliSec();
i = 0;
while (i < max_iters) {
ConstFunction(*first, *second);
++i;
}
long end_time = GetCurrentTimeInMilliSec();
std::cout << "time in const&: " << end_time - start_time << std::endl;
}
{
long start_time = GetCurrentTimeInMilliSec();
i = 0;
while (i < max_iters) {
ConstShardPtrFunction(first, second);
++i;
}
long end_time = GetCurrentTimeInMilliSec();
std::cout << "time in const shard_ptr&: " << end_time - start_time << std::endl;
}
return 1;
}
运行结果:
time in shard_ptr: 647
time in const&: 40
time in const shard_ptr&: 15
- 说明共享指针虽然是一个指针,但是其在传入的时会进行数值拷贝的,和值传递类似,但是又不完全相同。
- 其直接传入时,在函数内部重新make_shared时不改变原有数值,但是当进行指针操作时会改变原有数值。如:
void ShardPtrFunction( std::shared_ptr<std::string> first,
std::shared_ptr<std::string> second) {
// first被改变为qq,且被传回
first->assign("qq");
}
void ShardPtrFunction(std::shared_ptr<std::string> first,
std::shared_ptr<std::string> second) {
// first只是在函数内部被改变为qq,不会被传回
first = std::make_shared<std::string>("qq");
}
本文探讨了std::shared_ptr在函数调用中的内存拷贝问题,对比了普通const引用和const shared_ptr,并提供了优化建议。通过实例展示了shared_ptr在传值时的性能损耗,以及如何避免不必要的复制以提高效率。
1万+

被折叠的 条评论
为什么被折叠?



