类中唯一的指针
unique pointer within a class
假设我们有三个类:A, B, C。A和B都拥有一个指向类C的指针。永远不应该出现类A的两个实例共享指向对象C的同一个指针,但同时对象C可以被类B的实例自由指向的情况。
有没有办法在c++(11)中实现这个?
编辑= = = = = = = = = = = =
好的,让我们更详细地讲一下。当我创建对象C时,我将它们的指针添加到对象b中的容器中。对象a可能拥有或不拥有指向C的指针。重要的是,不超过一个a指向同一个C,这实际上可能是由于用户的错误而发生的。一旦A先验地指向C,它就应该一生都指向C。
我本来会选择唯一指针,但我需要它们的副本到B的容器中!
听起来,如果同一个指针被分配给多个A
实例,则需要抛出异常。
该解决方案可以跟踪已使用的指针以防止重赋值。不是线程安全的…如果需要的话,您必须修改它以添加同步。
class A
{
// The pointers used by all instances of A
static std::set<C*> used_ptrs;
// The pointer used by this instance of A
C* the_c;
// Sets the pointer if it is valid
void set_c( C* c )
{
if ( the_c )
throw std::runtime_error( "C pointer is already set in this A" );
if ( used_ptrs.count( c ) )
throw std::runtime_error( "C pointer is already set in another A" );
the_c = c;
used_ptrs.insert( c );
}
// The pointer is presumed to be unassigned at construction
A() : the_c(NULL) {}
// The pointer is removed from the set at destruction
~A()
{
if( the_c );
used_ptrs.erase( the_c );
}
// Copying A is invalid by your description
A( const A& ) = delete;
A& operator= ( const A& ) = delete;
}
我认为您需要在类内部做一些簿记,也许使用静态unordered_map
成员。我已经测试了下面的代码工作:
using namespace std;
struct C;
struct A
{
void SetPointerToC(C & aC)
{
if ( mAllC.find(&aC) != mAllC.end() )
assert(false); // multiple instances of A should not point to the same C
mAllC[&aC] = this;
mC = &aC;
}
~A()
{
mAllC.erase(mC);
}
private:
// A is not copyable as to prevent multiple A instances having
// mC with the same value
A(const A &);
A & operator=(const A &);
static unordered_map<C*, A*> mAllC;
C * mC;
};
unordered_map<C*, A*> A::mAllC;
struct C
{
};
int _tmain(int argc, _TCHAR* argv[])
{
A a;
A a2;
C c;
a.SetPointerToC(c); // works
a2.SetPointerToC(c); // assert!
return 0;
}
相关文章:
- 何时在引用或唯一指针上使用移动语义
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 如何使用Visual Studio 2017在C++中为参数化对象数组使用唯一指针
- 如何更改唯一指针向量的可见性
- 共享指针和具有自定义删除程序的唯一指针之间的语法差异背后的任何原因
- C++尝试深度复制唯一指针时出现内存访问冲突
- 使用 RTTI 克隆唯一指针的向量
- 为什么我无法创建唯一指针
- 如何将唯一指针的 std::vector 转换为原始指针的 std::span?
- 将唯一指针的指针传递给采用双指针的函数
- 在什么情况下,需要共享智能指针而无法使用唯一指针?
- C++唯一指针的向量
- 对带有唯一指针的 std::thread 使用类成员函数时出现编译错误
- 指向基类的唯一指针
- 添加要映射的对象的唯一指针
- 智能指针(唯一指针)和引用
- 唯一指针是否在堆或堆栈上分配内存?
- 尝试设置唯一指针布尔数组的值时BAD_ACCESS错误
- 使用唯一指针调用函数会使我的程序崩溃
- 智能指针(唯一指针)总是比普通指针更可取