Home > Software engineering >  Copy elision in initializer list?
Copy elision in initializer list?

Time:02-13

Consider this class

class A {
public:
    tracker tra;
    A(tracker _t) : tra(_t) {}
};

And call it through

A a {tracker()};

The object created by tracker() is never used until being stored in a.tra

Why don't the compiler optimize all the copy constructions away?

.

The tracker is defined here:

class tracker {
public:
    void mark(const char* v) {
        std::cout << v << ' ' << this << std::endl;
    }

    tracker() {
        mark("con");
    }

    tracker(const tracker& o) {
        mark("cpy");
    }

    tracker(tracker&& o) {
        mark("mov");
    }

    ~tracker() {
        mark("des");
    }

    tracker& operator=(const tracker&) {
        mark("=cp");
        return *this;
    }

    tracker& operator=(tracker&&) {
        mark("=mv");
        return *this;
    }
};

CodePudding user response:

Because the standard does not allow it. The copy constructor of tracker has observable side-effect here and this is not the case where compilers are allowed to perform copy elision ignoring the observable side-effects. (cppreference)

  • Related