struct template constructors

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jun 22 14:16:40 PDT 2017


On 06/22/2017 02:08 PM, Boris-Barboris wrote:
> On Thursday, 22 June 2017 at 20:05:46 UTC, Ali Çehreli wrote:
>> To be complete, 'auto ref' passes lvalues by reference and rvalues by
>> value, which you can detect with __traits(isRef):
>>
>> struct S{
>> }
>>
>> void foo()(auto ref S s) {
>>     static if (__traits(isRef, s)) {
>>         pragma(msg, "lvalue");
>>     } else {
>>         pragma(msg, "rvalue");
>>     }
>> }
>>
>> void main() {
>>     auto s = S();
>>     foo(s);
>>
>>     foo(S());
>> }
>>
>> Ali
>
> Thank you very much! And the last question:
> Is it guaranteed an all compilers, that:
> 1). destructor for said rvalue is called only once.
> 2). function taking auto ref parameter gets that exact (memory-wise)
> rvalue, for example:
>
> struct S {}
>
> S produce() { return S(); }
>
> consume(produce());
>
> void consume(auto ref S s)
> {
>   // s passed by value, but is exactly that struct returned by produce,
> as if it
>   // was RVO'd inside consume's stack frame.
>   // and S destructor called only once on consume's scope escape?
> }

I'm not sure whether it's RVO or moving in what condition, but yes, 
there will be no copy. You will get the bit representation of the 
constructed object.

And yes, there should be one destructor, which may be a no-op if you 
grab its resource and set it to null.

On all compilers...

Ali



More information about the Digitalmars-d-learn mailing list