Optimizing the number of constructor calls

后端 未结 2 2033
傲寒
傲寒 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: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.

提交回复
热议问题