这可能没有重写copy-ctors定义?
在C++ 11中,是的。你只需要声明构造并将其标记为拖欠:
struct X
{
// ...
private:
X(X const&) = default;
};
这将定义哪些将有相同的定义是一个隐含生成一个拷贝构造函数,但会private
。例如:
struct X
{
X() { } // Required because a user-declared constructor in
// the definition of X inhibits the implicit generation
// of a default constructor (even if the definition is
// defaulted!)
void foo()
{
// ...
X tmp = *this; // OK!
// ...
}
private:
X(X const&) = default; // Default definition, accessible to
// member functions of X only!
};
int main()
{
X x;
// X x2 = x; // ERROR if uncommented!
}
这是live example。
注意的是,在一个类的定义一个用户声明的构造(包括拷贝构造)抑制所述隐式生成一个缺省的构造的,即使其定义默认值。这就是为什么,例如,我不得不在上面的例子中明确声明X
的默认构造函数。