samedi 25 février 2017

Copy constructor not called when returning an object from someFun() in c++14 [duplicate]

This question already has an answer here:

#include <iostream>

class A
{
    private:
        std::string someMember;
    public:
        A(std::string _x): someMember(_x){
            std::cout << "  In A's constructor with _x: " << _x << '\n';
        }

        A(const A& someSibling){
            this -> someMember = someSibling.someMember;
            std::cout << "  In A's copy constructor with someSibling's someMember: " << someSibling.someMember << '\n';
        }

        void printA(){
            std::cout << "  A speaking: " << someMember << '\n';
        }
};

class B{
    private:
        A someObj;
        int someOtherMember;
    public:
        B(std::string& _y, int _z): someObj(_y), someOtherMember(_z){
            std::cout << "  In B's constructor with _y: " << _y << " and _z: " << _z << '\n';
        }

        B(A& _y, int _z): someObj(_y), someOtherMember(_z){
            std::cout << "  In B's constructor with _y: " << /* _y<< */ " and _z: " << _z << '\n';
        }

        B(const B& anotherObj): someObj(anotherObj.someObj){
            std::cout << "  In B's copy constructor with anotherObj.someOtherMember: " << anotherObj.someOtherMember << '\n';
            this -> someOtherMember = anotherObj.someOtherMember;
        }

        B(const B&& anotherObjRvalue): someObj(anotherObjRvalue.someObj){
            std::cout << "  In B's move constructor with anotherObj.someOtherMember: " << anotherObjRvalue.someOtherMember << '\n';
        }

        void printB(){
            someObj.printA();
            std::cout << "  B speaking: " << someOtherMember << '\n';
        }
};

B someFun(){
    std::cout << "  In someFun\n";
    std::string anotherTemp("my String");
    B temp(anotherTemp, 500);
    return temp;
}

int main(){

    auto res = someFun();
    res.printB();
    std::cout << "  ********** \n";
    return 0;
}

I was playing around with classes, and in the code above, when auto res = someFun() I expected that the copy constructor for B should be called but the copy constructor of B was not called and the output was:

In someFun
In A's constructor with _x: my String
In B's constructor with _y: my String and _z: 500
A speaking: my String
B speaking: 500
********** 

But I expected output to be:

In someFun
In A's constructor with _x: my String
In B's constructor with _y: my String and _z: 500
In B's copy constructor with anotherObj.someOtherMember: 500
A speaking: my String
B speaking: 500
********** 

So, my question is, why was the copy constructor of B not called in auto res = someFun() ?

Aucun commentaire:

Enregistrer un commentaire