有没有一种优雅的方式来交换C ++中的引用? [英] Is there an elegant way to swap references in C++?

查看:162
本文介绍了有没有一种优雅的方式来交换C ++中的引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时类引用其他类。对这些类实现 std :: swap()不能简单,因为它会导致原始实例而不是引用的交换。下面的代码说明了这种行为:

Sometimes classes are referencing other classes. Implementing std::swap() for such classes cannot be straightforward, because it would lead to swapping of original instances instead of references. The code below illustrates this behavior:

#include <iostream>

class A
{
   int& r_;
public:
   A(int& v) : r_(v) {}
   void swap(A& a)
   {
      std::swap(r_, a.r_);
   }
};

void test()
{
   int x = 10;
   int y = 20;

   A a(x), b(y);
   a.swap(b);

   std::cout << "x=" << x << "\n"
             << "y=" << y << "\n";
}

int main()
{
    test();
    return 0;
}

使用联合的简单解决方法:

A simple workaround with a union:

class A
{
   union
   {
      int& r_;
      size_t t_;
   };
public:
   A(int& v) : r_(v) {}
   void swap(A& a)
   {
      std::swap(t_, a.t_);
   }
};

这很有效,但不帅。有更好的方式来交换两个参考在C ++中吗?另外,C ++标准如何解释在一个联合中混合引用和值,考虑到在Stroustrup的C ++编程语言中预订'引用'被定义为

This is effective, but not handsome. Is there a nicer way to swap two references in C++? Also how does C++ standard explain mixing references and values in one union, considering that in Stroustrup's "The C++ Programming Language" book a 'reference' is defined as an 'alternative name of an object, an alias' (p.189).

推荐答案

重新使用就像代码获取一样不可移植。标准对于编译器如何实现引用没有任何要求。他们可以(并且大多数情况下)在引擎盖下使用指针,但这是永远不能保证的。更不用说 sizeof(size_t) sizeof(T *)无需相等

The union trick you're using is about as non-portable as code gets. The standard places no requirements whatsoever on how compilers implement references. They can (and most probably do) use pointers under the hood, but this is never guaranteed. Not to mention the fact that sizeof(size_t) and sizeof(T*) aren't required to be equal anyway.

您的问题的最佳答案是:如果您需要可分配/可交换的类,请不要使用引用成员。只需使用指针成员。毕竟,引用是不可重复的定义,但通过想要的类可交换,你想要的东西可重复。这是一个指针。

The best answer to your problem is: don't use reference members if you need an assignable/swappable class. Just use a pointer member instead. After all, references are non-reseatable by definition, yet by wanting the class swappable, you want something reseatable. And that's a pointer.

这篇关于有没有一种优雅的方式来交换C ++中的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆