gpt4 book ai didi

c++ - 安全赋值和复制交换习语

转载 作者:可可西里 更新时间:2023-11-01 16:31:43 25 4
gpt4 key购买 nike

<分区>

我正在学习 C++,我最近学习了(在堆栈溢出中)有关 copy-and-swap 惯用语的知识,对此我有几个问题。因此,假设我有以下使用 copy-and-swap 习语的类,例如:

class Foo {
private:
int * foo;
int size;

public:
Foo(size_t size) : size(size) { foo = new int[size](); }
~Foo(){delete foo;}

Foo(Foo const& other){
size = other.size;
foo = new int[size];
copy(other.foo, other.foo + size, foo);
}

void swap(Foo& other) {
std::swap(foo, other.foo);
std::swap(size, other.size);
}

Foo& operator=(Foo g) {
g.swap(*this);
return *this;
}

int& operator[] (const int idx) {return foo[idx];}
};

我的问题是,假设我有另一个类,它有一个 Foo 对象作为数据,但没有指针或其他可能需要自定义复制或分配的资源:

class Bar {
private:
Foo bar;
public:
Bar(Foo foo) : bar(foo) {};
~Bar(){};
Bar(Bar const& other) : bar(other.bar) {};
Bar& operator=(Bar other) {bar = other.bar;}
};

现在我有一系列的问题:

  1. 上面为 Bar 类实现的方法和构造函数是否安全?对 Foo 使用 copy-and-swap 后,我可以确保在分配或复制 Bar 时不会造成任何伤害吗?

  2. 在复制构造函数和交换中通过引用传递参数是强制性的吗?

  3. operator=的实参传值时,为该实参调用复制构造函数生成对象的临时拷贝,这样说对吗?这个拷贝是然后与 *this 交换的吗?如果我在 operator= 中通过引用传递,我会有一个大问题,对吗?

  4. 在复制和分配 Foo 时是否存在此习语无法提供完全安全的情况?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com