Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c++ Subject: Re: Don't be fooled by cpp.sh Date: Thu, 26 Dec 2019 10:54:48 -0800 Organization: None to speak of Lines: 46 Message-ID: <87woairk7b.fsf@nosuchdomain.example.com> References: <70391932-ccbc-4bc7-b693-881ab06eb6d3@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 8bit Injection-Info: reader02.eternal-september.org; posting-host="4f047e19a6a52fad2262d3feb4b60035"; logging-data="2828"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+S3ypZp2Mknx+Jiad+HbkA" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/26.3 (gnu/linux) Cancel-Lock: sha1:fZjj/3tpFIPa7kKIFn4orA4r51c= sha1:rBVkUNkqPtxtLmhNIEmqOeG1Uas= Xref: csiph.com comp.lang.c++:70671 Paavo Helde writes: > On 26.12.2019 11:46, boltar@nowhere.org wrote: [...] >> Of course dynamic memory allocation takes place - its not going to be on >> the stack if its in a container is it? > > If a std::optional is stored as an automatic variable then of course > it is allocated at stack. Where else? And this includes also its > contained value, as there is absolutely no reason to allocate it > dynamically. [...] > Fortunately programming is a concrete field and one can answer > concrete enough questions factually, no need to decide anything be > shouting louder than others. Here is a little program to find out > where a class A value contained in a std::optional is allocated. You > can run it with your favorite C++ compiler if you don't trust mine. [...] Your program only demonstrates that the T object is allocated within the optional object *for the implementation you used*. (Defining an optional type with a large parameter type T and printing its size would be a simpler way to demonstrate that.) I can easily imagine that a different implementation might store the T object outside the optional object, saving space when it's not present. What *does* prove that the T object is stored within the optional object is that the standard says it must be. C++17 23.6.3 [optional.optional] paragraph 1: Any instance of optional at any given time either contains a value or does not contain a value. When an instance of optional *contains a value*, it means that an object of type T, referred to as the optional object’s contained value, is allocated within the storage of the optional object. Implementations are not permitted to use additional storage, such as dynamic memory, to allocate its contained value. -- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com [Note updated email address] Working, but not speaking, for Philips Healthcare void Void(void) { Void(); } /* The recursive call of the void */