Why not always assign return values to const reference?

前端 未结 4 2093
半阙折子戏
半阙折子戏 2020-12-15 03:12

Let\'s say I have some function:

Foo GetFoo(..)
{
  ...
}

Assume that we neither know how this function is implemented nor the internals of

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-15 03:40

    These have semantic differences and if you ask for something other than you want, you will be in trouble if you get it. Consider this code:

    #include 
    
    class Bar
    {
        public:
        Bar() { printf ("Bar::Bar\n"); }
        ~Bar() { printf ("Bar::~Bar\n"); }
        Bar(const Bar&) { printf("Bar::Bar(const Bar&)\n"); }
        void baz() const { printf("Bar::Baz\n"); }
    };
    
    class Foo
    {
        Bar bar;
    
        public:
        Bar& getBar () { return bar; }
        Foo() { }
    };
    
    int main()
    {
        printf("This is safe:\n");
        {
            Foo *x = new Foo();
            const Bar y = x->getBar();
            delete x;
            y.baz();
        }
        printf("\nThis is a disaster:\n");
        {
            Foo *x = new Foo();
            const Bar& y = x->getBar();
            delete x;
            y.baz();
        }
        return 0;
    }
    

    Output is:

    This is safe:
    Bar::Bar
    Bar::Bar(const Bar&)
    Bar::~Bar
    Bar::Baz
    Bar::~Bar

    This is a disaster:
    Bar::Bar
    Bar::~Bar
    Bar::Baz

    Notice we call Bar::Baz after the Bar is destroyed. Oops.

    Ask for what you want, that way you're not screwed if you get what you ask for.

提交回复
热议问题