C++ Insights - Episode 46: Consider making your assignment operators lvalue only

แชร์
ฝัง
  • เผยแพร่เมื่อ 25 ธ.ค. 2024

ความคิดเห็น • 13

  • @garyp.7501
    @garyp.7501 3 หลายเดือนก่อน

    That is a good tip if you want to make your assignments always use a reference to the object.

  • @valentinsiltsenko
    @valentinsiltsenko 11 หลายเดือนก่อน +3

    Great tip. Thanks a lot!

  • @TheBuilder
    @TheBuilder 11 หลายเดือนก่อน +3

    I'll think about it

  • @stanbarvinsky1011
    @stanbarvinsky1011 11 หลายเดือนก่อน +3

    great tip! thank you

  • @VincentZalzal
    @VincentZalzal 11 หลายเดือนก่อน +1

    Have you seen any downsides to doing this? Does it prevent some common code idiom? I wonder if this could be made into a general guideline.

    • @David_Friberg
      @David_Friberg 11 หลายเดือนก่อน +1

      There are some downsides to this, but potentially the benefit holds their weight. See my comment above for details.

    • @VincentZalzal
      @VincentZalzal 11 หลายเดือนก่อน +1

      @@David_Friberg For some reason, I don't see your comment.

    • @davidf7196
      @davidf7196 11 หลายเดือนก่อน

      @@VincentZalzal Seems TH-cam's overzealously censored my comment, and does so even when I try to repost it. Trying from another account. What I wrote was:
      Note that this technique may unexpectedly break the rule of zero, in the cases where it would otherwise apply. As you declare the copy assignment op (even when explicitly defining it as defaulted) you suppress the implicit declaration of a defaulted move ctor and defaulted a move assignment operator. A mitigation comes with a cost: adding additional boilerplate code to bring us into rule of five, even if all special members are explicitly defined as defaulted. As an additional niche pitfall, it may also make aggregates into non-aggregates from C++20 and onward, as we need only user-declare a ctor to disqualify the class as an aggregate.
      Whilst this technique makes sense semantically, syntactically it can add a lot of noise, particularly in environments (automotive, safety-critical) where rule guidelines such as AUTOSAR C++14 (rule A12-0-1) will enforce rule of five if you cannot stick to rule of zero. Whilst this seems to have been addressed in MISRA C++:2023, I'm still leaning towards mitigation for to-rvalue assignment being enforced by static analysis (fully decidable) instead of via a language measure that comes with this kind of cost.

    • @David_Friberg
      @David_Friberg 11 หลายเดือนก่อน

      @@VincentZalzal For some reason my other (explanatory) comment keeps getting censored by TH-cam, no idea why. Instead, I posted it as a Q&A on r/cpp_questions, hopefully you can find it there.

    • @VincentZalzal
      @VincentZalzal 11 หลายเดือนก่อน

      @@David_FribergFound it, thanks.