C++:智能指针和流畅设计模式与参考



在被高级语言宠坏了一辈子之后,我正在努力学习C++。

我想在课堂上使用流畅的设计模式,但我担心我在某个地方犯了错误,牺牲了性能。

假设我有一个类Builder,它有一些成员属性和方法。所有的方法看起来都是这样的:

Builder &doSomething(SomeTypeThatCouldBeAClassOrAPrimitive &thing)
{
// do stuff, such as
// modify a class member
memberThing = "something";

return *thing;
} 

然后说我是这样使用的:

unique_ptr<Builder> builder(new Builder());
builder->doSomething(someVal)
.doAnotherThing(someOtherVal)
.doAFinalThing(someOtherOtherVal);

仅仅从提供的代码来看,我是做错了什么,还是可以更有效地完成一些事情?

如果我需要提供更多信息,请告诉我。

这里没有任何错误,但也不需要在堆上分配Builder对象。考虑一下:

Builder builder;
builder.doSomething(someVal)
.doAnotherThing(someOtherVal)
.doAFinalThing(someOtherOtherVal);

您甚至可以使用临时Builder并完全删除变量:

Builder{}.doSomething(someVal)
.doAnotherThing(someOtherVal)
.doAFinalThing(someOtherOtherVal);

最新更新