开发者

mismatch in constructors/destructors count [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

C++ basic constructors/vectors problem (1 constructor, 2 destructors)

I have got the code:

#include <iostream>
class A   
{    
public:    
    A() { std::cout<<"A::A"<<std::endl; }    
    ~A()开发者_开发技巧 { std::cout<<"A::~A"<<std::endl; }
};

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

void Func( A a ){}

int main()
{
    B b;
    Func(b);
}

in VS2010EE output will be:

A::A
B::B
A::~A //why twice? Once on gcc!
A::~A
B::~B
A::~A

But, when we have copy constructor, output is:

A::A
B::B
A::A(copy)
A::~A
B::~B
A::~A


That's a bit unfortunate. VS should avoid that second copy; are all optimizations on? Presumably, it's calling a copy constructor on the A portion of b to create the argument (ie slicing it), then copying that object onto the stack again for the function call. (In the first example, your constructor for A isn't being called because the generated copy constructor doesn't print output.) When you provide a copy constructor, it must create the copy directly on the stack.


You're not counting all the constructors. In the first case, the copy constructor is invoked to create a copy of the object when calling Func (because the function takes its parameter by value).

When you don't define a copy constructor yourself, the compiler will generate one for you. And the compiler-generated copy constructor doesn't print anything out, so it doesn't figure in your output.


If I understand correctly, you're effectively asking this:

Why does VS2010 create an additional temporary when I have no copy constructor?

The only answer I have is 'because it's allowed to'. It seems that it gets optimised away when you're using gcc, and also gets optimised away when you provide a user-defined copy constructor.

The behaviour is a little odd, but it's perfectly compliant. If all C++ compilers performed identically, we'd only need one compiler...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜