自定义复制构造函数并添加字段

发布于 2024-07-16 09:00:40 字数 344 浏览 7 评论 0原文

此内容重复.

在 C++ 中,有时您必须自己实现复制构造函数(通常当您将指针作为成员时)。 通过编译器生成的复制构造函数,这有一个缺点,即当您添加成员字段并忘记在复制构造函数中添加复制行时,就会遇到问题,并且通常很难追踪。 我喜欢防御性编程,这让我有点担心。

一种解决方案是使用 memcpy,然后正确处理指针,但据我了解,不鼓励这样做。

Duplicate of this.

In C++ you sometimes have to implement the copy constructor yourself (when you have pointer as a member usually). Over compiler generated copy constructor this has the disadvantage that when you add a member field and forget to add the copying line in the copy constructor, you have a problem, which is often hard to track down. I like to program defensively and this worries me a bit.

One solution would be to use memcpy and then just handle the pointers properly, but this is discouraged as I understand it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

安静被遗忘 2024-07-23 09:00:40

不要使用裸指针 - 如果需要,请使用智能指针来为您执行复制操作。 然后,您不再需要编写复制构造函数 - 在过去五年中我只编写了一个复制构造函数。

Don't use naked pointers - use a smart pointer that will do the copy for you, if needed. Yo then no longer need to write a copy constructor - I have only written a single one in the past five years.

放赐 2024-07-23 09:00:40

不要这样做 - 如果有人添加了指针成员变量并忘记了复制构造函数,那么无论哪种方式都不起作用 - 我建议您添加一个编译时断言 链接文本 在类的 sizeof 的复制构造函数中 - 如果 sizeof 将更改 - 编译断言将失败并且代码将不会编译直到有人更改条件 - 有人更改位于有关确保正确复制所有成员的注释旁边的条件并且不这样做的可能性非常低;)

Don't do it - it won't work either way if someone adds a pointer member variable and forgets about the copy constructor - I'd suggest you add a compile time assert link text in the copy constuctor for the sizeof of your class - if the sizeof will change - the compile assert will fail and the code will not compile untill someone changes the condition - the possibility of someone changing the condition that sits next to a comment about making sure to copy all members correctly and not doing that is quite low ;)

恋竹姑娘 2024-07-23 09:00:40

不,不要使用 memcpy。 您面临着覆盖您甚至不知道存在的数据(例如虚函数表)的风险。此外,如果您添加的字段本身就是一个指针,那么您还没有解决任何问题。

针对这种情况进行防御性编程的最佳实践是:

  • 无论何时添加字段,都要养成检查类构造函数、析构函数等的习惯

  • 进行自动化测试

  • 使用内存调试工具,例如Purify(也可以使用开源工具,可能会有所帮助。)

No, do not use memcpy. You run the risk of overwriting data that you don't even know exists (vtables, for example.) Also, if the field that you've added is itself a pointer, then you haven't solved anything.

The best practices for programming defensively for this situation are:

  • Be in the habit of examining your class constructors, destructors, etc. whenever you add fields

  • Have automated tests

  • Use memory debugging tools such as Purify (open-source tools are also available that may help.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文