问题写作交换功能

时间:2014-10-02 12:26:56

标签: c++ swap

我正在努力为包含指针数组的结构编写(我的第一个)交换函数。

struct Foo
{
    unsigned int Count;
    int* Items;

    Foo()
    {
        Count = 0;
        Items = 0;
    }

    Foo(const Foo& foo)
    {
        Items = 0;
        swap(foo); // cannot convert argument 1 from 'const Foo' to 'Foo *'
    }

    Foo(const unsigned int itemCount)
    {
        Count = itemCount;
        Items = new int[itemCount];
        for (int i = 0; i < itemCount; i++)
        {
            Items[i] = 123;
        }
    }

    Foo& operator=(const Foo& foo)
    {
        swap(foo); // cannot convert argument 1 from 'const Foo' to 'Foo *'

        return *this;
    }

    void swap(Foo* foo)
    {
        unsigned int a(Count);
        int* b(Items);

        Count = foo->Count;
        Items = foo->Items;

        foo->Count = a;
        foo->Items = b;
    }

    ~Foo()
    {
        delete[] Items;
    }
};
  1. 任何人都可以帮我解释语法吗?

  2. 我这样做的原因是为了帮助我理解它如何与指针数组一起使用?

  3. 我在网上看到它是异常安全的,因为它没有分配新内存来做到这一点?肯定ab都分配了内存,因此如果内存不可用就会失败?

  4. 编辑: 基于lucacox的回答...

    void swap(Foo* foo1, Foo* foo2)
    {
        unsigned int a(foo1->Count);
        int* b(foo1->Items);
    
        foo1->Count = foo2->Count;
        foo1->Items = foo2->Items;
    
        foo2->Count = a;
        foo2->Items = b;
    }
    

    这样称呼......

    swap(&foo, this); // cannot convert argument 1 from 'const Foo' to 'Foo *'
    

    我仍然遇到const转换错误?

3 个答案:

答案 0 :(得分:1)

您可能无法更改常量对象。因此,您可能无法将成员函数交换应用于复制构造函数中Foo类型的对象的常量引用。而且,将它与类的复制构造函数一起使用是没有意义的。替换此复制构造函数

Foo(const Foo& foo)
{
    Items = 0;
    swap(foo); // cannot convert argument 1 from 'const Foo' to 'Foo *'
}

这两个(一个是没有交换的复制构造函数,另一个是带交换的移动构造函数)

Foo( const Foo& foo ) : Count( foo.Count )  
{
    Items = new int[Count];
    std::memcpy( Items, foo.Items, Count * sizeof( int ) );
    // std::copy( foo.Items, foo.Items + foo.Count, Items );
}

Foo( Foo&& foo) : Count( 0 ), Items( 0 )
{
    swap(foo);
}

与复制赋值运算符相同的操作是您应该在不使用swap的情况下定义复制赋值运算符,而使用swap的移动赋值运算符。

只有成员函数swap应声明为void swap( Foo & )

答案 1 :(得分:0)

之间的冲突 美孚和放大器; operator =(const Foo&amp; foo) 这需要foo的一致性, 和swap,实际上修改它的参数是c ++中的基本参数。它甚至引起了语言标准的变化,增加了“rvalues”和“move constructors”。谷歌“c ++移动语义”获得更多解释。

答案 2 :(得分:-1)

错误是由不同的参数声明引起的:

Foo& operator(const Foo& foo)

将参数foo声明为对Foo对象的const(不可修改)引用。而

void swap(Foo* foo)

将参数foo声明为指向Foo对象的指针。

你不能转换为const Foo&amp;对于Foo *,它们是不同的类型。

我建议通过传递它来实现交换功能Foo *:

void swap(Foo* foo1) {
    int count = this->Count;
    int* items = this->Items;

    this->Count = foo1->Count;
    this->Items = foo1->Items;

    foo1->Count = count;
    foo1->Items = items;
}