我有一个类成员,它是std::shared_ptr
到其他对象的向量,但是我并没有真正使用shared_ptr
来表达共享所有权;我只需要它们,因为我想使用std::weak_ptr
作为检查向量中的对象是否仍然存在的简单方法。
由于我并不真正需要或想要共享所有权,我正在考虑从访问者函数返回这些对象的原始指针向量,我认为这比复制shared_ptr
更快。这是我的代码:
#include <iostream>
#include <memory>
#include <chrono>
#include <vector>
using namespace std;
struct Owner {
//Constructor: populate the member vector with 50 shared_ptrs to doubles
Owner() {
for (int i = 0; i != 50; ++i)
numbers.push_back(make_shared<double>(i));
{}
//Member vector of shared pointers
vector<shared_ptr<double>> numbers;
//Accesor function that returns a copy of the vector
vector<shared_ptr<double>> GetSharedPtrs() {
return numbers;
}
//Accesor function that returns the raw pointers from the vector
vector<double*> GetRawPtrs() {
vector<double*> ret;
for (const auto& num : numbers)
ret.push_back(num.get());
return ret;
}
};
基于以下测试(MSVC 2013,默认发布模式优化级别),我惊讶地发现这两种方法的速度几乎相同:
int main() {
Owner own;
vector<shared_ptr<double>> shared;
vector<double*> raw;
chrono::high_resolution_clock::time_point start, stop;
for (int i = 0; i != 10; ++i) {
start = chrono::high_resolution_clock::now();
for (int j = 0; j != 10000; ++j)
shared = own.GetSharedPtrs();
stop = chrono::high_resolution_clock::now();
cout << "Shared pointers: \t" << chrono::duration_cast<chrono::milliseconds>(stop - start).count() << " ms" << endl;
start = chrono::high_resolution_clock::now();
for (int j = 0; j != 10000; ++j)
raw = own.GetRawPtrs();
stop = chrono::high_resolution_clock::now();
cout << "Raw pointers: \t\t" << chrono::duration_cast<chrono::milliseconds>(stop - start).count() << " ms" << endl;
cout << endl;
}
return 0;
}
在所有10次迭代中,每个访问器方法的执行时间约为15 ms。我的直觉是复制shared_ptr
比调用get()
方法更昂贵,但这似乎并非如此。我的直觉是错的,还是我的测试方法存在缺陷?