5

I have a very basic question. I have the sample code shown as below:

class Member {
public:
    Member() {
        std::cout << "Default constructor called" << std::endl;
    }

    Member(int a) {
        std::cout << "Constructor with int called: " << a << std::endl;
    }

    Member(const Member& rhs) {
        std::cout << "Copy constructor is called" << std::endl;
    }

    Member(Member&& rhs) {
        std::cout << "Move constructor is called" << std::endl;
    }

    Member& operator=(Member&& rhs) {
        std::cout << "Move operator is called" << std::endl;
        return *this;
    }

    Member& operator=(const Member& rhs) {
        std::cout << "Assignment operator is called" << std::endl;
        return *this;
    }
}

class Entity {
 public:
    Entity()
    {}

    Entity(int a)
        : member_(Member(a))    
    {
        std::cout << "Entity constructor with member_ init list is called" << std::endl;
    }

    Entity(std::string desc, int a) {
        std::cout << "Entity constructor WITHOUT member_ init list called" << std::endl;
        member_ = Member(a);
    }
private:
    Member member_;
};

int main()
{
    Entity b(8);
}

The output is

Constructor with int called: 8
Entity constructor with member_ init list is called

I would expect the Member's copy constructor to be invoked here, since in Entity(int a) : member_(Member(a)) , we first construct a Member with a, then copy it to member_. How is member_ gets assigned in this case if not via the copy constructor? Thank you!

bunbohue
  • 63
  • 6
  • 7
    [Copy elision](https://en.cppreference.com/w/cpp/language/copy_elision) – user4581301 May 04 '22 at 14:44
  • *I would expect...* Your expectations need amending. The language requires constructors to have a specific semantic, and is allowed to elide them. So if they have *side effects*, there is no guarantee that those *side effects* will occur. (So those side effects had better be benign, and not critical.) – Eljay May 04 '22 at 15:07
  • @bunbohue the move constructor would be a better match than copy constructor, iff direct initialization AKA copy elision was not involved. – Red.Wave May 04 '22 at 15:30
  • @Red.Wave the move constructor didn't get invoked either. Elijay: Thanks! – bunbohue May 04 '22 at 15:45
  • See the first comment above. – Red.Wave May 04 '22 at 15:47

0 Answers0