gpt4 book ai didi

c++ - 具有指向用户定义类型指针的类的复制构造函数

转载 作者:太空狗 更新时间:2023-10-29 23:14:56 25 4
gpt4 key购买 nike

我见过很多类的复制构造函数的例子,类的成员变量是指向 int 或 char 的指针。有人可以建议为具有成员 ptrB 的类 A 编写复制构造函数的正确方法,该成员 ptrB 是指向用户定义的类 B 的指针。

这是正确的吗:

class A {
private:
B *ptrB;
public:
A() { ptrB = new B; }
A(const A& other);
~A();
}

A::A(const A& other)
{
ptrB = new B;
*(ptrB) = *(other.ptrB);
}

如果 ptrB 是这样定义的:

shared_ptr<B> ptrB;

然后是这个?

A::A(const A& other)
{
ptrB(new B);
*(ptrB) = *(other.ptrB);
}

谢谢。

最佳答案

因为您用“深度复制”标记了帖子,我假设您希望复制构造函数执行此操作。使用 shared_ptr 生成的默认复制构造函数深复制。

我建议复制类指针成员有两种一般形式。

Deep(const Deep& other): ptr(new T(*other.ptr)) {}

Shallow(const Shallow& other) = default;

请注意,像这样的浅拷贝不适用于 unique_ptr。通过设计,unique_ptr 可以防止这种情况。

下面是每一个的例子,显示了不同之处。注意,在实践中使用原始版本很容易导致内存泄漏。重要的一点是浅拷贝之后,修改拷贝就是修改原件。

#include <memory>
#include <iostream>

template<typename T, typename TPtr>
struct Deep
{
TPtr ptr;

Deep() : ptr(new T) {}

T get() const { return *ptr; }
void set(T t) { *ptr = t; }

Deep(const Deep& other): ptr(new T(*other.ptr)) {}
};

template<typename T, typename TPtr>
struct Shallow
{
TPtr ptr;

Shallow() : ptr(new T) {}

T get() const { return *ptr; }
void set(T t) { *ptr = t; }

Shallow(const Shallow& other) = default;
};

template<typename T>
using raw_ptr = T*;

template<typename T>
void test(const T& a1)
{
auto a2 = a1;
a2.set(a2.get() + 1);
std::cout << a1.get() << " " << a2.get() << std::endl;
}

using std::shared_ptr;

int main()
{
Deep<int, raw_ptr<int> > rawDeep;
rawDeep.set(1);
test(rawDeep);

Deep<int, shared_ptr<int> > sharedDeep;
sharedDeep.set(1);
test(sharedDeep);

Shallow<int, raw_ptr<int> > rawShallow;
rawShallow.set(1);
test(rawShallow);

Shallow<int, shared_ptr<int> > sharedShallow;
sharedShallow.set(1);
test(sharedShallow);
}

http://ideone.com/NltfUO

关于c++ - 具有指向用户定义类型指针的类的复制构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31304372/

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