Optimizing the number of constructor calls

后端 未结 2 2034
傲寒
傲寒 2021-02-19 13:04

At work we have a class with an expensive constructor so we would like it to be called as few times as possible. We looked through the uses of it and tried to make the code more

相关标签:
2条回答
  • 2021-02-19 13:30

    If the compiler cannot inline append, then it cannot determine that the return value is target object. Then it doesn't know that the temporary is being returned, and cannot construct it in place.

    You would have the same behavior with:

    Imaginary tmp(*this);
    return tmp.append(rhs);
    

    If the return value of append is opaque to the compiler (defined in another compilation unit), it prevents the optimization.

    0 讨论(0)
  • 2021-02-19 13:34

    Stephan T. Lavavej mentions in http://channel9.msdn.com/Events/GoingNative/2013/Don-t-Help-the-Compiler that (N)RVO only happens when the type of the returned value is exactly the same as the type returned from the method.

    For example:

    string foo() {string tmp; return tmp;}  // Same type, uses NRVO or automatic move.
    string foo() {const string& tmp = "bar"; return tmp;}  // Types differ, no NRVO, nor automatic move.
    string foo() {string tmp; string& ref = tmp; return ref;}  // Types differ, no NRVO, nor automatic move.
    string foo() {string tmp; return (string&) tmp;}  // Types differ, no NRVO, nor automatic move.
    

    (cf. http://coliru.stacked-crooked.com/a/79e79e5bb0350584)

    I guess append returns a reference to Imaginary, and as Imaginary& is not of the same type as Imaginary this prevents (N)RVO.

    0 讨论(0)
提交回复
热议问题