在两个构造函数之间进行选择

编程入门 行业动态 更新时间:2024-10-27 12:30:29
本文介绍了在两个构造函数之间进行选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

问题:我有一个具有两个构造函数的不可复制对象。我需要创建一个对象与一个构造函数,然后在一些常见的代码中使用它: -

Problem: I have a non-copyable object with two constructors. I need to create an object with one of the constructors and then use it within some common code:-

对于可复制对象,它将看起来像这样,

With a copyable object it would look like this, and be easy:

Object a; if (condition) a = Object(p1); else a = Object(p2,p3,p4); a.doSomething();

但是,对象是不可复制的,所以我不得不这样做:

But, the object is non-copyable, so I've had to do this:

boost::scoped_ptr<Object> a; if (condition) a = new Object(p1); else a = new Object(p2,p3,p4); a->doSomething();

这太麻烦了。有没有更好的解决方案?

This feels too complex. Is there a better solutiuon?

推荐答案

这是一个非常可怕的黑客,假设 Object 是默认可构造的:

Here's a very terrible hack, assuming Object is default-constructible:

Object a; a.~Object(); if (condition) { ::new (&a) Object(p1); } else { ::new (&a) Object(p2, p3, p4); }

不要使用这个。

Don't use this.

另一个选项是使用联合,但是你需要在该设置中手动调用析构函数。

Another option is using a union, but you'll need to invoke the destructor manually in that setup as well.

一个更清洁的解决方案可以通过 Boost.Optional (使用就地工厂)。 (感谢@ K-Ballo挖掘细节!)

A cleaner solution could be achieved with Boost.Optional (using in-place factories). (Thanks to @K-Ballo for digging up the details!)

#include <boost/optional.hpp> #include <boost/utility/in_place_factory.hpp> struct Object { explicit Object(int) {} explicit Object(int, float, std::string) {} Object(Object const &) = delete; Object(Object &&) = delete; Object & operator=(Object const &) = delete; Object & operator=(Object &&) = delete; }; boost::optional<Object> a; if (condition) { a = boost::in_place(0); } else { a = boost::in_place(0, 1.0f, "two" ); }

更多推荐

在两个构造函数之间进行选择

本文发布于:2023-07-11 09:32:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1093594.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   两个

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!