编译器生成的构造函数
这只是一个简单的问题,可以正确理解当您使用这样的构造函数创建一个类时会发生什么:
class A
{
public:
A() {}
};
我知道不会生成默认构造函数,因为它已经定义了,而是由编译器生成的复制和赋值构造函数,或者换句话说,不会生成默认构造函数 。我需要 声明一个私有复制构造函数和一个私有赋值运算符以防止这种情况发生?
class A
{
private:
// needed to prevent automatic generation?
A( const A& );
A& operator=( const A& );
public:
A() {}
};
This is just a quick question to understand correctly what happens when you create a class with a constructor like this:
class A
{
public:
A() {}
};
I know that no default constructor is generated since it is already defined but are copy and assignment constructors generated by the compiler or in other words do i need to
declare a private copy constructor and a private assignment operator in order to prevent this from happening?
class A
{
private:
// needed to prevent automatic generation?
A( const A& );
A& operator=( const A& );
public:
A() {}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,即使您声明了自己的默认构造函数,仍然会创建复制构造函数和复制赋值运算符。
仅当您分别在类定义中声明自己的复制构造函数或复制赋值运算符时,才会抑制这些创建。
请注意,可以同时拥有自己的复制构造函数和编译器提供的复制构造函数:
但是,标准允许编译器接受此代码 - 但效果类似于具有未定义的行为:程序格式不正确,但没有警告/该程序需要错误。 (早期的 GCC 版本不拒绝此代码,最近的版本拒绝它)。
Yes, copy constructor and copy assignment operators are still created even if you declare your own default constructor.
The creation of those are only suppressed if you declare your own copy constructor or copy assignment operator in the class definition respectively.
Note that it is possible to have both your own copy constructor, and a compiler provided one:
The Standard however allows compilers to accept this code - but the effect is similar to having undefined behavior: The program is ill-formed, but no warning/error is required for that program. (early GCC versions don't reject this code, recent ones reject it).
是的。无论其他构造函数和运算符如何,始终都会创建复制构造函数、赋值运算符和析构函数。
如果您想禁用其中一个,那么您所拥有的就是完美的。这也很常见。
Yes. The copy constructor, assignment operator, and destructor are always created regardless of other constructors and operators.
If you want to disable one, what you've got there is perfect. It's quite common too.
如果您想禁用复制和赋值,那么最好从具有私有复制构造函数和赋值运算符的类继承(
boost::noncopyable
是一个现成的)。1)减少重复打字。
2)自我记录(希望如此)。
3)更严格地检查这些操作是否无法被调用(类本身,或者类本身也不能复制 - 这将导致编译器错误,而不是链接器错误)。
4)不会隐藏默认构造函数:)
If you want to disable copying and assigning, then it might be better to inherit from a class that has a private copy constructor and assignment operator (
boost::noncopyable
is a ready-made one).1) Less repetitive typing.
2) Self-documenting (hopefully).
3) Stronger checks that those operations can't be invoked (the class itself, nor the friends can make copies either - that would result in a compiler, not a linker error).
4) Won't hide the default constructor :)