【问题标题】:Operator overloading, Rvalues, C++运算符重载、右值、C++
【发布时间】:2020-12-16 06:38:14
【问题描述】:

考虑一个结构

template<typename T, size_t N>
struct Something {
    std::array<T,N> args;

    // Some constructors

};

现在让我们为Something&lt;T&gt; 重载= 运算符。事实上,我可以通过两种方式实现它。

第一道

Something& operator=(const Something& rhs){
    // an implementation with copy semantics
}

Something& operator=(Something&& rhs) {
    // an implementation with move semantics
}

第二种方式

Something& operator=(Something rhs){
    // implement with move semantics
}

所以,我的问题是最标准的方式最优化的方式来重载First WaySecond方式

【问题讨论】:

  • 您是在问一般情况,还是针对您的特定情况?一般来说,第二种方式可能不是最优的。
  • 这取决于你的目的,指针引用和内存复制的选择

标签: c++ copy operator-overloading move-semantics rvalue


【解决方案1】:

对于这种特殊情况,您不应实现赋值运算符。编译器已经为你做到了:

#include <array>
#include <cstddef>

template<typename T, size_t N>
struct Something {
    std::array<T,N> args;
};

int main() {
    Something<int,42> a;
    Something<int,42> b;
    a = b;
}

Demo

对于一般情况,我将您推荐给What are the basic rules and idioms for operator overloading?。并考虑到并非所有东西都可以移动,也不是所有东西都可以复制。而且,有时一个动作只是一个副本。因此,这取决于。

【讨论】:

  • 其实我问的是一般情况)
  • @HrantNurijanyan 您想询问一般情况,但您确实询问了此示例;)
  • 你不能使用std::array::size_type 并且(然后)不需要包含 cstddef 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 2013-03-30
  • 2016-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-27
相关资源
最近更新 更多