C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Fwd: Pass derived object by reference to single parameter delegated templated constructors

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Mon, 6 May 2024 10:18:35 -0400
On Mon, May 6, 2024 at 4:46 AM David wang via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
> We should pass a derived argument object by reference to the single parameter delegated templated constructors declared in its base class.
>
> struct base {
>
> public : base() {}
>
> template <typename T> base(T x) {}
>
> };
>
>
> struct derived : public base {
>
> public: derived() {}
>
> derived(derived& that): base(that) {}
>
> };
>
>
> int main() {
>
> derived d1;
>
> derived d2 = d1;
>
> return 0;
>
> }
>
>
> The assignment d2 = d1 causes derived(derived& that) to be called.
>
> The initialzier base(that) causes the object that(which is a derived object) to be copied before template <typename T> base(T x) {} to be called, which causes derived(derived& that) to be called again.
>
>
> Before passing a derived object to the single parameter templated constructor,
>
> the copying process for the derived object is currently underway.
> The single parameter Delegated C++ constructor's copy semantics
> simply copy the portion declared in the derived object's base class.
> The portion declared in the derived class do not need to be copied or constructed again.

This is way too special-case to implement. It's ultimately on the user
to prevent this from happening. `base`'s constructor uses template
argument deduction. That function takes its parameter by value. If you
use template argument deduction on such a function and pass it a type
which is a reference, it will copy the parameter. This *needs* to be a
hard-and-fast rule.

Received on 2024-05-06 14:18:48