Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: copy by value to function params produce two objects in vs2012

Here's code that produces different output in g++ 4.7 and vs2012 (cl17).

#include <iostream>

using namespace std;

class A
{
public:
    A() { cout << "1" << endl; }
    ~A() { cout << "2" << endl; }
};

class B : public A
{
public:
    B() { cout << "3" << endl; }
    ~B() { cout << "4" << endl; }
};

void func(A a) {}

int main()
{
    B b;
    func(b);
    return 0;
}

The GCC output is 13242, while cl outputs 132242.

Why does the cl compiler produce a second A object while it makes a copy on the stack, and for what purpose?

like image 734
user1823018 Avatar asked Nov 14 '12 08:11

user1823018


Video Answer


1 Answers

It seems to be a compiler bug.
The C++ Standard does not use the term Object Slicing, You are passing an object of the type B to a function which receives an parameter of the type A. The compiler will apply the usual overload resolution to find the appropriate match. In this case:
The Base class A has compiler provided copy constructor, which will take a reference to A and in absence of other conversion functions this is the best match and should be used by the compiler.

Note that if better conversion was available, it would be used. For eg: If A had a constructor A::A( B const& ), in addition to the copy constructor, then this constructor would be used, instead of the copy constructor.

like image 198
Alok Save Avatar answered Oct 23 '22 07:10

Alok Save