一个类是否可以有一个构造函数,该构造函数具有一个参数:对同一类型的另一个实例的引用,但不是复制构造函数?
所以我有一个代表小部件树的 Widget 类,我想要有一个小部件的构造函数,它引用父小部件。该类还有一个显式删除的复制构造函数。这是否意味着引用父窗口小部件的构造函数仍被视为复制构造函数?这是否意味着如果我将此类的实例存储在 std::vector 或其他容器中,可能会发生意外的事情?
class Widget
{
public:
Widget();
Widget(Widget& parentWidget); // Is this a copy constructor?
~Widget();
Widget(Widget&&) = delete;
Widget& operator=(Widget&&) = delete;
Widget(const Widget&) = delete;
Widget& operator=(const Widget&) = delete;
};
So I have a class Widget that represents a tree of widgets, I want to have a constructor for widget that takes a reference to the parent widget. The class also has an explicitly deleted copy constructor. Does this mean that the constructor taking a reference to the parent widget is still considered a copy constructor? Does this mean unexpected things could happen if I were to store an instance of this class in a std::vector or some other container?
class Widget
{
public:
Widget();
Widget(Widget& parentWidget); // Is this a copy constructor?
~Widget();
Widget(Widget&&) = delete;
Widget& operator=(Widget&&) = delete;
Widget(const Widget&) = delete;
Widget& operator=(const Widget&) = delete;
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
是的,它有资格作为复制构造函数,即使没有
const
。我不确定标准容器是否会对此感到困惑,但你的程序员同事肯定会。
使用参考以外的东西。
Widget(Widget *parentWidget);
可以工作。Yes, it qualifies as a copy constructor, even without the
const
.I'm not sure if the standard containers will get confused by it, but your fellow programmers definitely will.
Use something other than a reference.
Widget(Widget *parentWidget);
would work.