问题:我有一个具有两个构造函数的不可复制对象。我需要创建一个对象与一个构造函数,然后在一些常见的代码中使用它: -
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" ); }更多推荐
在两个构造函数之间进行选择
发布评论