lundi 30 novembre 2015

C++ literal passed to const reference leads to automatic construction

If I call the "func(const generic& ref)" with an integer as argument (instead of a 'generic' object), the constructor generic(int _a) will be called to create a new object.

class generic
{
    public:
    int a;

    generic() {}

    generic(int _a) : a(_a)
    {
        std::cout << "int constructor was called!";
    }

    generic(const generic& in) : a(in.a)
    {
        std::cout << "copy constructor was called!";
    }
};

void func(const generic& ref)
{
    std::cout << ref.a;
}

int main()
{
    generic g(2);

    func(g); // this is good.

    func(generic(4)); // this is good.

    func(8); // this is good...... ?

    return 0;
}

The last "func(8)" call creates a new object using the constructor generic(int _a). Is there a name for this kind of construction? Shouldn't the programmer explicitly construct an object before passing the argument? Like this:

func(generic(8));

Is there any benefit in passing the integer alone (other than saving time)?

Aucun commentaire:

Enregistrer un commentaire