From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: (qmail 21400 invoked by alias); 8 Aug 2008 22:23:39 -0000 Received: (qmail 21390 invoked by uid 22791); 8 Aug 2008 22:23:38 -0000 X-Spam-Check-By: sourceware.org Received: from vms173001pub.verizon.net (HELO vms173001pub.verizon.net) (206.46.173.1) by sourceware.org (qpsmtpd/0.31) with ESMTP; Fri, 08 Aug 2008 22:22:56 +0000 Received: from [10.10.1.168] ([63.106.93.177]) by vms173001.mailsrvcs.net (Sun Java System Messaging Server 6.2-6.01 (built Apr 3 2006)) with ESMTPA id <0K5A009LJZHRQXCA@vms173001.mailsrvcs.net> for gcc-help@gcc.gnu.org; Fri, 08 Aug 2008 17:22:40 -0500 (CDT) Date: Sat, 09 Aug 2008 01:09:00 -0000 From: John Fine Subject: Is this code wrong? In-reply-to: <489C4C8F.4060804@verizon.net> Cc: gcc-help Message-id: <489CC728.5040603@verizon.net> MIME-version: 1.0 Content-type: text/plain; charset=UTF-8; format=flowed Content-transfer-encoding: 7bit References: <489BEDB7.2020905@loskot.net> <489C4C8F.4060804@verizon.net> User-Agent: Thunderbird 2.0.0.16 (Windows/20080708) X-IsSubscribed: yes Mailing-List: contact gcc-help-help@gcc.gnu.org; run by ezmlm Precedence: bulk List-Id: List-Archive: List-Post: List-Help: Sender: gcc-help-owner@gcc.gnu.org X-SW-Source: 2008-08/txt/msg00080.txt.bz2 While investigating an unrelated (really) problem, I came across a bunch of examples of a construct that I'm pretty sure shouldn't work, yet it seems to be working. Am I misunderstanding this (is there some reason this code should work)? This is all in code belonging to my employer, written by another employee, so I can't quote a large enough chunk for you to test. But I think the concepts are simple enough for someone to answer based on the info I can provide. An inline function declares a std::vector, initializes it, then returns it. The calling function assigns that return value to a const&. My understanding is that the return of the local object makes a temporary copy of that object, which exists only during the calling statement. So the reference is to that temporary object, which no longer exists. inline std::vector get_vector() { std::vector result; ... code to put contents into result ... return result; } in some other function std::vector const& local_vector = get_vector(); unrelated code read the contents from local_vector What is the scope of the temporary vector that catches the return value from the function? I thought that scope should be just that statement. Could the scope be the rest of the {} containing the statement? Is this code working just because of a lazy destructor (frees the memory, but leaves the pointer and contents intact and nothing happens to reallocate that memory soon enough to trash it)? Or is the destructor really not called until later?