Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

After reading this article on Herb Sutter's blog, I experimented a bit and ran into something that puzzles me. I am using Visual C++ 2005, but I would be surprised if this was implementation dependent.

Here is my code:

#include <iostream>

using namespace std;

struct Base {
    //Base() {}
    ~Base() { cout << "~Base()" << endl; }
};

int main()
{
    const Base & f = Base();
}

When run, it displays "~Base()" twice... But if I un-comment the constructor, it displays it only once!

Does anyone have an explanation for this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
271 views
Welcome To Ask or Share your Answers For Others

1 Answer

This IS implementation dependent.

The standard allows a copy to occur when binding a temporary to a const reference. In your case, VC++ performs a copy only when the constructor is implicitly defined. This is unexpected, but permitted.

C++1x will fix this.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...