Clang modifies return value in destructor?

前端 未结 1 1622
囚心锁ツ
囚心锁ツ 2021-01-04 17:41

While trying to write a class that times the duration between calling it\'s constructor and destructor, I ran into what I think is a bug in clang. (Edit: it\'s not a bug; it

相关标签:
1条回答
  • 2021-01-04 18:24

    Short answer: due to NRVO, the output of the program may be either 0 or the actual duration. Both are valid.


    For background, see first:

    • in C++ which happens first, the copy of a return object or local object's destructors?
    • What are copy elision and return value optimization?

    Guideline:

    • Avoid destructors that modify return values.

    For example, when we see the following pattern:

    T f() {
        T ret;
        A a(ret);   // or similar
        return ret;
    }
    

    We need to ask ourselves: does A::~A() modify our return value somehow? If yes, then our program most likely has a bug.

    For example:

    • A type that prints the return value on destruction is fine.
    • A type that computes the return value on destruction is not fine.
    0 讨论(0)
提交回复
热议问题