请注意,我正在使用C++ 03,并且delete
d函数没有提供给我。防止编译器在C++中考虑隐式声明的拷贝构造函数03
我试图设计一个不可复制的对象,并防止编译器考虑该类上的隐式声明的复制构造函数。这是我正在开发的单元测试夹具。
请考虑我有两个主要对象:一个核心库对象Root
和一个派生的特殊对象测试对象Branch
。我试图开发一个测试夹具类,Fixture
,它处理与核心Root
对象建立&对象的细节。因此,这是什么,我到目前为止已经建立了一个简单的例证:
(Here is an ideone link与下面的相同的代码,但我定义我自己noncopyable
)
#include <boost/utility.hpp>
#include <boost/noncopyable.hpp>
class Root
{
};
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Root& mRoot;
};
class Branch
:
public Root,
public Fixture
{
public:
Branch()
:
Fixture (*this)
{
}
};
int main()
{
Branch branch;
}
编译这会导致:
main.cpp: In constructor ‘Branch::Branch()’:
main.cpp:30:23: error: call of overloaded ‘Fixture(Branch&)’ is ambiguous
main.cpp:30:23: note: candidates are:
main.cpp:13:5: note: Fixture::Fixture(Root&)
main.cpp:8:7: note: Fixture::Fixture(const Fixture&)
这是不可能的*,以防止C++ 03编译器隐含地声明Fixture
的复制构造函数,除非我自己声明至少一个。但即使有:
Fixture (*this)
我希望编译器根本就没有考虑这些拷贝构造函数:
class Fixture
:
public boost::noncopyable
{
public:
Fixture (Root& root)
:
mRoot (root)
{
}
private:
Fixture (const Fixture&);
Fixture (Fixture&);
Root& mRoot;
};
...编译器将仍然在Branch
的初始化列表初始化Fixture
时考虑这些private
声明。
我可以用我自己做一个小的被扭曲做到这一点:
Fixture (static_cast <Root&> (*this))
...但我宁愿不要,因为它是一个有点臭我的鼻子和非复制能力是语义我要去从boost::noncopyable
推导Fixture
。
有没有一种方法,以防止考虑在这种情况下隐式声明的拷贝构造函数,编译器不会在调用点更改代码:
Fixture (*this)
?
- “这是不可能的......”:标准C++ 03:12.8/4, “特殊成员函数”:
如果类定义不明确声明一个副本 构造函数,一个是隐式声明的。
C++ 11中删除的函数甚至有帮助吗?删除的函数仍然参与重载解析。 –
@KerrekSB:老实说,我不知道。如果你是对的,他们参与解决,那么我认为他们不会帮助。 –
我相信[模板化构造函数](http://ideone.com/nHhzEi)应该明确优先... –