【发布时间】:2019-11-24 23:54:14
【问题描述】:
我有一个包含 (Poco) 互斥锁的 C++ 类:
class ClassWithMutex
{
public:
ClassWithMutex();
virtual ~ClassWithMutex();
Poco::Mutex mMyMutex;
private:
ClassWithMutex(const ClassWithMutex& );
ClassWithMutex& operator=(const ClassWithMutex& other);
};
还有另一个类,使用它:
class ClassHavingAClassWithMutex
{
public:
ClassHavingAClassWithMutex();
~ClassHavingAClassWithMutex();
ClassWithMutex A;
private:
ClassHavingAClassWithMutex(const ClassHavingAClassWithMutex&);
ClassHavingAClassWithMutex& ClassHavingAClassWithMutex::operator=(const ClassHavingAClassWithMutex& other);
};
尝试为 ClassHavingAClassWithMutex 创建包装器时,出现错误:
Error C2248 'ClassWithMutex::operator =': cannot access private member declared in class 'ClassWithMutex' mvr C:\builds\vs2015\mvr\python_package\src\mvr\mvrPYTHON_wrap.cxx 6493
Swig 生成的代码如下所示:
SWIGINTERN PyObject *_wrap_ClassWithMutex_mMyMutex_get(PyObject *SWIGUNUSEDPARM(self), PyObject *args) {
PyObject *resultobj = 0;
ClassWithMutex *arg1 = (ClassWithMutex *) 0 ;
void *argp1 = 0 ;
int res1 = 0 ;
PyObject *swig_obj[1] ;
Poco::Mutex result;
if (!args) SWIG_fail;
swig_obj[0] = args;
res1 = SWIG_ConvertPtr(swig_obj[0], &argp1,SWIGTYPE_p_ClassWithMutex, 0 | 0 );
if (!SWIG_IsOK(res1)) {
SWIG_exception_fail(SWIG_ArgError(res1), "in method '" "ClassWithMutex_mMyMutex_get" "', argument " "1"" of type '" "ClassWithMutex *""'");
}
arg1 = reinterpret_cast< ClassWithMutex * >(argp1);
{
SWIG_PYTHON_THREAD_BEGIN_ALLOW;
result = ((arg1)->mMyMutex);
SWIG_PYTHON_THREAD_END_ALLOW;
}
resultobj = SWIG_NewPointerObj((new Poco::Mutex(static_cast< const Poco::Mutex& >(result))), SWIGTYPE_p_Poco__Mutex, SWIG_POINTER_OWN | 0 );
return resultobj;
fail:
return NULL;
}
以及从这一行发出的错误:
if (arg1) (arg1)->A = *arg2;
and
resultobj = SWIG_NewPointerObj((new Poco::Mutex(static_cast< const Poco::Mutex& >(result))), SWIGTYPE_p_Poco__Mutex, SWIG_POINTER_OWN | 0 );
Swig 接口文件:
%immutable
%include "aiClassWithMutex.h"
%include "ClassHavingAClassWithMutex.h"
%mutable
关于如何用 Swig 正确包装上述类有什么建议吗?我在上面的课程中将复制和分配ctor的私有化,以防止任何复制,但似乎swig坚持这样做?
【问题讨论】:
-
为什么要有私有的拷贝构造函数?如果您想禁用复制,请考虑“三法则”,或者对于更新的 C++,请考虑“五法则”。
-
@UlrichEckhardt 用于防止复制的私有复制构造函数,因为互斥体。
-
有点多余,因为 mutex 成员使类既不可复制又不可分配。分配是一些代码尝试的。