gpt4 book ai didi

c++ - 使用 placement new 转移对象所有权

转载 作者:行者123 更新时间:2023-11-28 08:20:23 26 4
gpt4 key购买 nike

我有一个 Visual Studio 2008 C++ 项目,其中的类管理无法复制的资源。我已经实现了按引用传输结构语义(ala std::auto_ptr)。

class Test;

struct Test_Ref
{
Test& ref_;
Test_Ref( Test& t ) : ref_( t ) { };
private:
Test_Ref& operator=( Test_Ref const& );
}; // struct Test_Ref

class Test
{
public:
explicit Test( int f = 0 ) : foo_( f ) { };

Test( Test& other ) : foo_( other.Detach() ) { };

Test& operator=( Test& other )
{
foo_ = other.Detach();
return *this;
};

Test( Test_Ref other ) : foo_( other.ref_.Detach() ) { };

Test& operator=( Test_Ref other )
{
foo_ = other.ref_.Detach();
return *this;
};

operator Test_Ref() { return Test_Ref( *this ); };

private:

int Detach()
{
int tmp = foo_;
foo_ = 0;
return tmp;
};

// resource that cannot be copied.
int foo_;
}; // class Test

不幸的是,当我将此模式与使用 placement-new 的库一起使用时,出现编译器错误:

.\test.cpp(58) : error C2558: class 'Test' : no copy constructor available or copy constructor is declared 'explicit'
.\test.cpp(68) : see reference to function template instantiation 'void Copy<Test>(T *,const T &)' being compiled
with
[
T=Test
]

例如:

template< class T > inline void Copy( T* p, const T& val ) 
{
new( p ) T( val );
}

int _tmain( int /*argc*/, _TCHAR* /*argv*/[] )
{
Test* __p = new Test();
Test __val;
Copy( __p, __val );
return 0;
}

我如何修改 Test 以便它可以与 placement new 一起使用并仍然保留其所有权语义?

谢谢,保罗H

最佳答案

关注 main 函数,因为它应该表明您的预期语义,有两个大问题:首先,您没有分配内存,这意味着如果编译器将处理代码,它会导致 UB(会尝试在放置新操作中通过 NULL 地址调用 Test 的构造函数。

std::auto_ptr 的用户都知道另一个问题:复制构造函数的签名采用非 const 引用,这意味着您不能在 const 对象上调用它。另一方面,您试图在 Copy 模板中调用复制构造函数,该模板 promise 不会更改第二个参数引用的对象:

template <typename T>
void Copy( T* p, T& o ) {
new (p) T( o ); // would work, object is non-const
}

最后,我不确定是否由于复制到问题中,但我不确定您一开始提供的引用包装器类的意图是什么,因此您可能需要澄清一下。

关于c++ - 使用 placement new 转移对象所有权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6024095/

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