1. 基本方式
std::shared_ptr<TestClass> p(new TestClass("hello world", 123));
这句话调用了两次内存管理器:
- 创建TestClass实例
- 创建引用计数对象
2. make_shared方式
std::shared_ptr<TestClass> p = std::make_shared<TestClass>("hello world", 123);
auto p = std::make_shared<TestClass>("hello world", 123);
2.1 缺点-低效率
void fiddle(std::shared_ptr<Foo> f);
shared_ptr<Foo> myFoo = make_shared<Foo>();
fiddle(myFoo);
函数执行的时候,存在无谓的原子性增加和减小操作,而且操作都使用了完整的内存屏障。
使用普通指针可以避免无谓的原子操作。