问题描述
问题:我有一个具有两个构造函数的不可复制对象。我需要创建一个对象与一个构造函数,然后在一些常见的代码中使用它: -
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); }
(使用)。 (感谢@ 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" ); }
这篇关于在两个构造函数之间进行选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!