the usage of copy-constructor method?

Viewed 98

In my code, I used inner-class as an iterator for another class.

To simplify the situation, the code can be shown as follows:

class A {
public:
    class B {
    public:
        explicit B(void):idx(3){}
        B(const B&b)  {
            idx = 4;    // never be called
        }
    private:
        int idx=0;
    };
    B getB()
    {   return A::B();   }
};
void test2(){
    A a;
    A::B b = a.getB();  // b.idx ends with value of 3
}

The problem is that, in test2() , while running A::B b = a.getB();, the copy-constructor method wasn't called. And the b ends with value 3. Why is this?

For another problem confused me

class A {
public:
    class B {
    public:
        explicit B(void):idx(3){}
        explicit B(const B&b) {}  // C2440, cannot convert from "A::B" to "A::B"
    private:
        int idx=0;
    };
    B getB()
    {   return A::B();  }
};

Why will C2440 ocurrs with two types exactly the same?

2 Answers

What you are seeing is copy elision. In order to make it easier for optimizers to speed up the generated code, the C++ standard allows copy constructors to be skipped in certain situations.

C++ language does not guarantee the side effects of copy (nor of move) constructors to be observable in the abstract machine. This non-guarantee lets the compiler avoid temporary objects when they are not necessary, thereby avoiding copying of those objects in the concrete machine.

Your program relies on the side effects of a copy constructor. This is bad; Don't do it.

Related