英文:
Swapping private unique pointers with a public method
问题
我有一个类,其中有一个私有的 unique_ptr 成员,我想要暴露一个公共的 swap 函数,用来交换它的 unique_ptr 成员的所有权和提供的其他对象的 unique_ptr 成员的所有权。我该如何做?
```cpp
class A { // A 是多态类型,派生自 A1、A2 等
private:
std::unique_ptr<B> b;
public:
void swap_b(A& other) {
std::swap(b, other.b); // 我想要交换 A.b 和 other.b
}
};
class B { // B 是多态类型
private:
std::unique_ptr<C> c; // c 也是多态类型
public:
void swap_C(B& other) {
std::swap(c, other.c);
}
};
int main() {
std::unique_ptr<A> alphaOne = std::make_unique<A1>(...);
std::unique_ptr<A> alphaTwo = std::make_unique<A2>(...);
alphaOne->swap_b(*alphaTwo); // unique_ptr alphaOne->b->c 应该与 alphaTwo->b->c 交换所有权
}
我有一个 vector<std::unique_ptr<A>>
,我想从中获取任意两个元素并调用 swap 函数来交换它们的 b.c unique_ptr。我该如何实现这个?
std::vector<std::unique_ptr<A>> myVector;
// 假设 myVector 至少包含两个元素
size_t index1 = 0; // 第一个元素的索引
size_t index2 = 1; // 第二个元素的索引
myVector[index1]->swap_b(*myVector[index2]); // 交换两个元素的 unique_ptr A->b->c
英文:
I have a class with a private unique_ptr member and I want to expose a public swap function which will swap ownership of its unique_ptr member with that of the provided other. How can I do so?
class A{ // a is polymorphic type, derivatives A1, A2, etc
private:
unique_ptr<B> b;
public:
void swap_b(A??? other) {
A.b.swap_c(other.b) // I want to swap A.b.c with other.b.c
}
};
class B{ // b is polymorphic type
private:
unique_ptr<C> c; // c is also polymorphic type
public:
void swap_C(B??? other) {
B.c.swap(other.c)
}
};
int main() {
unique_ptr<A> alphaOne = make_unique<A1>(...);
unique_ptr<A> alphaTwo = make_unique<A2>(...);
alphaOne.swap(alphaTwo); // the unique_ptr alphaOne.b.c should swap ownership with alphaTwo.b.c
}
I have a vector<unique_ptr<A>>
, from which I want to grab any two elements and call swap on them to swap their b.c unique_ptrs. How can I achieve this?
答案1
得分: 2
- 基类的析构函数在通过基类指针销毁实例时应该是
virtual
的。
英文:
I am unsure if I am missing something, but a simple reference should suffice:
#include <memory>
using namespace std;
class C {};
class B {
private:
unique_ptr<C> c;
public:
void swap(B& other){ c.swap(other.c); }
};
class A {
private:
unique_ptr<B> b;
public:
virtual ~A() = default; // See note 1.
void swap(A& other){ b.swap(other.b); }
};
class A1:public A{};
class A2:public A{};
int main() {
unique_ptr<A> alphaOne = make_unique<A1>();
unique_ptr<A> alphaTwo = make_unique<A2>();
alphaOne.swap(alphaTwo);
}
- The destructor of the base class should be
virtual
when you destroy instances via a base class pointer.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论