开发者

return *this c++

if you have a clear() function that clears all elements in an array, do you use the void type or the referens to the type you are working with and returning *this.

Ex.

void Vector<T>::clear() {   
}

or

Vector& Vector<T>::clear(){
    return *this
}

I don't really understand when to return "t开发者_开发知识库his" and when to use void type.


I assume returning *this is useful to chain API calls. obj.doSomething().doSomethingElseAfterwards(). So calls where chaining is useful, such as add are good candidates for *this. And methods where chaining is not very useful might return void.

Personally I'm not fond of this chaining style, but many people like the fluent APIs this allows.


It's up to you.

For reference, std::vector::clear returns void.


In this particular case, there's no especially good reason to return the current object that I can think of, other than to enable dubious code like

myVector.clear().add(somethingNew);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜