C++ 如何在C++中正确实现工厂方法模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5120768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement the factory method pattern in C++ correctly
提问by Kos
There's this one thing in C++ which has been making me feel uncomfortable for quite a long time, because I honestly don't know how to do it, even though it sounds simple:
C++ 中有一件事情让我感到很不舒服很长一段时间,因为老实说我不知道该怎么做,尽管这听起来很简单:
How do I implement Factory Method in C++ correctly?
如何在 C++ 中正确实现工厂方法?
Goal: to make it possible to allow the client to instantiate some object using factory methods instead of the object's constructors, without unacceptable consequences and a performance hit.
目标:允许客户端使用工厂方法而不是对象的构造函数来实例化某个对象,而不会产生不可接受的后果和性能损失。
By "Factory method pattern", I mean both static factory methods inside an object or methods defined in another class, or global functions. Just generally "the concept of redirecting the normal way of instantiation of class X to anywhere else than the constructor".
“工厂方法模式”是指对象内部的静态工厂方法或另一个类中定义的方法,或全局函数。一般只是“将类 X 的正常实例化方式重定向到构造函数以外的任何其他地方的概念”。
Let me skim through some possible answers which I have thought of.
让我浏览一下我想到的一些可能的答案。
0) Don't make factories, make constructors.
0)不要制造工厂,制造构造器。
This sounds nice (and indeed often the best solution), but is not a general remedy. First of all, there are cases when object construction is a task complex enough to justify its extraction to another class. But even putting that fact aside, even for simple objects using just constructors often won't do.
这听起来不错(实际上通常是最好的解决方案),但不是一般的补救措施。首先,在某些情况下,对象构造是一项足够复杂的任务,足以证明其提取到另一个类是合理的。但即使把这个事实放在一边,即使对于只使用构造函数的简单对象通常也行不通。
The simplest example I know is a 2-D Vector class. So simple, yet tricky. I want to be able to construct it both from both Cartesian and polar coordinates. Obviously, I cannot do:
我知道的最简单的例子是 2-D Vector 类。如此简单,但也很棘手。我希望能够从笛卡尔坐标和极坐标中构建它。显然,我不能这样做:
struct Vec2 {
Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!
// ...
};
My natural way of thinking is then:
我的自然思维方式是:
struct Vec2 {
static Vec2 fromLinear(float x, float y);
static Vec2 fromPolar(float angle, float magnitude);
// ...
};
Which, instead of constructors, leads me to usage of static factory methods... which essentially means that I'm implementing the factory pattern, in some way ("the class becomes its own factory"). This looks nice (and would suit this particular case), but fails in some cases, which I'm going to describe in point 2. Do read on.
哪个,而不是构造函数,导致我使用静态工厂方法......这基本上意味着我正在以某种方式实现工厂模式(“类成为它自己的工厂”)。这看起来不错(并且适合这种特殊情况),但在某些情况下会失败,我将在第 2 点中进行描述。请继续阅读。
another case: trying to overload by two opaque typedefs of some API (such as GUIDs of unrelated domains, or a GUID and a bitfield), types semantically totally different (so - in theory - valid overloads) but which actually turn out to be the same thing - like unsigned ints or void pointers.
另一种情况:试图通过某些 API 的两个不透明 typedef(例如不相关域的 GUID,或 GUID 和位域)重载,类型在语义上完全不同(因此 - 理论上 - 有效的重载)但实际上结果是同样的事情——比如无符号整数或空指针。
1) The Java Way
1)Java方式
Java has it simple, as we only have dynamic-allocated objects. Making a factory is as trivial as:
Java 很简单,因为我们只有动态分配的对象。建立工厂就像:
class FooFactory {
public Foo createFooInSomeWay() {
// can be a static method as well,
// if we don't need the factory to provide its own object semantics
// and just serve as a group of methods
return new Foo(some, args);
}
}
In C++, this translates to:
在 C++ 中,这转化为:
class FooFactory {
public:
Foo* createFooInSomeWay() {
return new Foo(some, args);
}
};
Cool? Often, indeed. But then- this forces the user to only use dynamic allocation. Static allocation is what makes C++ complex, but is also what often makes it powerful. Also, I believe that there exist some targets (keyword: embedded) which don't allow for dynamic allocation. And that doesn't imply that the users of those platforms like to write clean OOP.
凉爽的?很多时候,确实如此。但是,这迫使用户只能使用动态分配。静态分配使 C++ 变得复杂,但也常常使其强大。另外,我相信存在一些不允许动态分配的目标(关键字:嵌入式)。这并不意味着这些平台的用户喜欢编写干净的 OOP。
Anyway, philosophy aside: In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.
无论如何,抛开哲学:在一般情况下,我不想强迫工厂的用户被限制为动态分配。
2) Return-by-value
2) 按值返回
OK, so we know that 1) is cool when we want dynamic allocation. Why won't we add static allocation on top of that?
好的,所以我们知道 1) 当我们想要动态分配时很酷。为什么我们不在其上添加静态分配?
class FooFactory {
public:
Foo* createFooInSomeWay() {
return new Foo(some, args);
}
Foo createFooInSomeWay() {
return Foo(some, args);
}
};
What? We can't overload by the return type? Oh, of course we can't. So let's change the method names to reflect that. And yes, I've written the invalid code example above just to stress how much I dislike the need to change the method name, for example because we cannot implement a language-agnostic factory design properly now, since we have to change names - and every user of this code will need to remember that difference of the implementation from the specification.
什么?我们不能通过返回类型重载?哦,我们当然不能。因此,让我们更改方法名称以反映这一点。是的,我写了上面的无效代码示例只是为了强调我不喜欢更改方法名称的必要性,例如因为我们现在无法正确实现与语言无关的工厂设计,因为我们必须更改名称 - 和此代码的每个用户都需要记住实现与规范的差异。
class FooFactory {
public:
Foo* createDynamicFooInSomeWay() {
return new Foo(some, args);
}
Foo createFooObjectInSomeWay() {
return Foo(some, args);
}
};
OK... there we have it. It's ugly, as we need to change the method name. It's imperfect, since we need to write the same code twice. But once done, it works. Right?
好的……我们有了。这很丑陋,因为我们需要更改方法名称。这是不完美的,因为我们需要编写两次相同的代码。但是一旦完成,它就起作用了。对?
Well, usually. But sometimes it does not. When creating Foo, we actually depend on the compiler to do the return value optimisation for us, because the C++ standard is benevolent enough for the compiler vendors not to specify when will the object created in-place and when will it be copied when returning a temporary object by value in C++. So if Foo is expensive to copy, this approach is risky.
嗯,通常。但有时不会。在创建 Foo 时,我们实际上依赖编译器为我们做返回值优化,因为 C++ 标准足够仁慈,编译器供应商无需指定何时就地创建对象以及何时在返回时复制对象在 C++ 中按值临时对象。因此,如果 Foo 的复制成本很高,则这种方法是有风险的。
And what if Foo is not copiable at all? Well, doh. (Note that in C++17 with guaranteed copy elision, not-being-copiable is no problem anymore for the code above)
如果 Foo 根本不可复制怎么办?嗯,嗯。(请注意,在保证复制省略的 C++17 中,对于上面的代码,不可复制不再是问题)
Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.
结论:通过返回对象来创建工厂确实是某些情况下的解决方案(例如前面提到的二维向量),但仍然不是构造函数的通用替代品。
3) Two-phase construction
3) 两期建设
Another thing that someone would probably come up with is separating the issue of object allocation and its initialisation. This usually results in code like this:
有人可能会想到的另一件事是将对象分配及其初始化的问题分开。这通常会导致如下代码:
class Foo {
public:
Foo() {
// empty or almost empty
}
// ...
};
class FooFactory {
public:
void createFooInSomeWay(Foo& foo, some, args);
};
void clientCode() {
Foo staticFoo;
auto_ptr<Foo> dynamicFoo = new Foo();
FooFactory factory;
factory.createFooInSomeWay(&staticFoo);
factory.createFooInSomeWay(&dynamicFoo.get());
// ...
}
One may think it works like a charm. The only price we pay for in our code...
人们可能认为它就像一种魅力。我们在代码中支付的唯一价格...
Since I've written all of this and left this as the last, I must dislike it too. :) Why?
由于我已经写了所有这些并将其作为最后一个,所以我也一定不喜欢它。:) 为什么?
First of all... I sincerely dislike the concept of two-phase construction and I feel guilty when I use it. If I design my objects with the assertion that "if it exists, it is in valid state", I feel that my code is safer and less error-prone. I like it that way.
首先......我真的很不喜欢两阶段建设的概念,当我使用它时我会感到内疚。如果我设计我的对象时断言“如果它存在,则它处于有效状态”,我觉得我的代码更安全,更不容易出错。我喜欢这样。
Having to drop that convention AND changing the design of my object just for the purpose of making factory of it is.. well, unwieldy.
不得不放弃那个约定并改变我的对象的设计只是为了制造它的工厂......好吧,笨拙。
I know that the above won't convince many people, so let's me give some more solid arguments. Using two-phase construction, you cannot:
我知道以上内容不会说服很多人,所以让我提供一些更可靠的论据。使用两阶段构造,您不能:
- initialise
const
or reference member variables, - pass arguments to base class constructors and member object constructors.
- 初始化
const
或引用成员变量, - 将参数传递给基类构造函数和成员对象构造函数。
And probably there could be some more drawbacks which I can't think of right now, and I don't even feel particularly obliged to since the above bullet points convince me already.
可能还有一些我现在想不到的缺点,我什至没有特别的义务,因为上述要点已经说服了我。
So: not even close to a good general solution for implementing a factory.
所以:甚至不接近实现工厂的良好通用解决方案。
Conclusions:
结论:
We want to have a way of object instantiation which would:
我们想要一种对象实例化的方法,它可以:
- allow for uniform instantiation regardless of allocation,
- give different, meaningful names to construction methods (thus not relying on by-argument overloading),
- not introduce a significant performance hit and, preferably, a significant code bloat hit, especially at client side,
- be general, as in: possible to be introduced for any class.
- 无论分配如何,都允许统一实例化,
- 为构造方法提供不同的、有意义的名称(因此不依赖于参数重载),
- 不会引入显着的性能损失,最好不会引入显着的代码膨胀,尤其是在客户端,
- 是通用的,例如:可以为任何类引入。
I believe I have proven that the ways I have mentioned don't fulfil those requirements.
我相信我已经证明我提到的方法不能满足这些要求。
Any hints? Please provide me with a solution, I don't want to think that this language won't allow me to properly implement such a trivial concept.
任何提示?请给我一个解决方案,我不想认为这种语言不允许我正确实现这样一个微不足道的概念。
采纳答案by Sergei Tachenov
First of all, there are cases when object construction is a task complex enough to justify its extraction to another class.
首先,在某些情况下,对象构造是一项足够复杂的任务,足以证明其提取到另一个类是合理的。
I believe this point is incorrect. The complexity doesn't really matter. The relevance is what does. If an object can be constructed in one step (not like in the builder pattern), the constructor is the right place to do it. If you really need another class to perform the job, then it should be a helper class that is used from the constructor anyway.
我认为这一点是不正确的。复杂性并不重要。相关性是什么。如果一个对象可以一步构造出来(不像在构建器模式中那样),构造器就是正确的地方。如果你真的需要另一个类来执行这项工作,那么它应该是一个从构造函数中使用的帮助类。
Vec2(float x, float y);
Vec2(float angle, float magnitude); // not a valid overload!
There is an easy workaround for this:
有一个简单的解决方法:
struct Cartesian {
inline Cartesian(float x, float y): x(x), y(y) {}
float x, y;
};
struct Polar {
inline Polar(float angle, float magnitude): angle(angle), magnitude(magnitude) {}
float angle, magnitude;
};
Vec2(const Cartesian &cartesian);
Vec2(const Polar &polar);
The only disadvantage is that it looks a bit verbose:
唯一的缺点是它看起来有点冗长:
Vec2 v2(Vec2::Cartesian(3.0f, 4.0f));
But the good thing is that you can immediately see what coordinate type you're using, and at the same time you don't have to worry about copying. If you want copying, and it's expensive (as proven by profiling, of course), you may wish to use something like Qt's shared classesto avoid copying overhead.
但好处是您可以立即看到您正在使用的坐标类型,同时您不必担心复制。如果您想要复制,并且成本很高(当然,通过分析证明),您可能希望使用类似Qt 的共享类的东西来避免复制开销。
As for the allocation type, the main reason to use the factory pattern is usually polymorphism. Constructors can't be virtual, and even if they could, it wouldn't make much sense. When using static or stack allocation, you can't create objects in a polymorphic way because the compiler needs to know the exact size. So it works only with pointers and references. And returning a reference from a factory doesn't work too, because while an object technically canbe deleted by reference, it could be rather confusing and bug-prone, see Is the practice of returning a C++ reference variable, evil?for example. So pointers are the only thing that's left, and that includes smart pointers too. In other words, factories are most useful when used with dynamic allocation, so you can do things like this:
至于分配类型,使用工厂模式的主要原因通常是多态性。构造函数不能是虚拟的,即使可以,也没有多大意义。使用静态或堆栈分配时,不能以多态方式创建对象,因为编译器需要知道确切的大小。所以它只适用于指针和引用。从工厂返回引用也不起作用,因为虽然技术上可以通过引用删除对象,但它可能相当混乱且容易出错,请参阅返回 C++ 引用变量的做法是否邪恶?例如。所以指针是唯一剩下的东西,也包括智能指针。换句话说,工厂在与动态分配一起使用时最有用,因此您可以执行以下操作:
class Abstract {
public:
virtual void do() = 0;
};
class Factory {
public:
Abstract *create();
};
Factory f;
Abstract *a = f.create();
a->do();
In other cases, factories just help to solve minor problems like those with overloads you have mentioned. It would be nice if it was possible to use them in a uniform way, but it doesn't hurt much that it is probably impossible.
在其他情况下,工厂只是帮助解决小问题,例如您提到的过载问题。如果可以以统一的方式使用它们会很好,但它可能是不可能的并没有太大伤害。
回答by Martin York
Simple Factory Example:
简单工厂示例:
// Factory returns object and ownership
// Caller responsible for deletion.
#include <memory>
class FactoryReleaseOwnership{
public:
std::unique_ptr<Foo> createFooInSomeWay(){
return std::unique_ptr<Foo>(new Foo(some, args));
}
};
// Factory retains object ownership
// Thus returning a reference.
#include <boost/ptr_container/ptr_vector.hpp>
class FactoryRetainOwnership{
boost::ptr_vector<Foo> myFoo;
public:
Foo& createFooInSomeWay(){
// Must take care that factory last longer than all references.
// Could make myFoo static so it last as long as the application.
myFoo.push_back(new Foo(some, args));
return myFoo.back();
}
};
回答by Evan Teran
Have you thought about not using a factory at all, and instead making nice use of the type system? I can think of two different approaches which do this sort of thing:
你有没有想过根本不使用工厂,而是很好地利用类型系统?我可以想到两种不同的方法来做这种事情:
Option 1:
选项1:
struct linear {
linear(float x, float y) : x_(x), y_(y){}
float x_;
float y_;
};
struct polar {
polar(float angle, float magnitude) : angle_(angle), magnitude_(magnitude) {}
float angle_;
float magnitude_;
};
struct Vec2 {
explicit Vec2(const linear &l) { /* ... */ }
explicit Vec2(const polar &p) { /* ... */ }
};
Which lets you write things like:
这让您可以编写以下内容:
Vec2 v(linear(1.0, 2.0));
Option 2:
选项 2:
you can use "tags" like the STL does with iterators and such. For example:
您可以像 STL 对迭代器等那样使用“标签”。例如:
struct linear_coord_tag linear_coord {}; // declare type and a global
struct polar_coord_tag polar_coord {};
struct Vec2 {
Vec2(float x, float y, const linear_coord_tag &) { /* ... */ }
Vec2(float angle, float magnitude, const polar_coord_tag &) { /* ... */ }
};
This second approach lets you write code which looks like this:
第二种方法可让您编写如下所示的代码:
Vec2 v(1.0, 2.0, linear_coord);
which is also nice and expressive while allowing you to have unique prototypes for each constructor.
这也很好且富有表现力,同时允许您为每个构造函数拥有独特的原型。
回答by mabg
You can read a very good solution in: http://www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
您可以在以下位置阅读非常好的解决方案:http: //www.codeproject.com/Articles/363338/Factory-Pattern-in-Cplusplus
The best solution is on the "comments and discussions", see the "No need for static Create methods".
最好的解决办法是关于“评论和讨论”,请参阅“不需要静态创建方法”。
From this idea, I've done a factory. Note that I'm using Qt, but you can change QMap and QString for std equivalents.
从这个想法,我做了一个工厂。请注意,我使用的是 Qt,但您可以更改 QMap 和 QString 以获得 std 等效项。
#ifndef FACTORY_H
#define FACTORY_H
#include <QMap>
#include <QString>
template <typename T>
class Factory
{
public:
template <typename TDerived>
void registerType(QString name)
{
static_assert(std::is_base_of<T, TDerived>::value, "Factory::registerType doesn't accept this type because doesn't derive from base class");
_createFuncs[name] = &createFunc<TDerived>;
}
T* create(QString name) {
typename QMap<QString,PCreateFunc>::const_iterator it = _createFuncs.find(name);
if (it != _createFuncs.end()) {
return it.value()();
}
return nullptr;
}
private:
template <typename TDerived>
static T* createFunc()
{
return new TDerived();
}
typedef T* (*PCreateFunc)();
QMap<QString,PCreateFunc> _createFuncs;
};
#endif // FACTORY_H
Sample usage:
示例用法:
Factory<BaseClass> f;
f.registerType<Descendant1>("Descendant1");
f.registerType<Descendant2>("Descendant2");
Descendant1* d1 = static_cast<Descendant1*>(f.create("Descendant1"));
Descendant2* d2 = static_cast<Descendant2*>(f.create("Descendant2"));
BaseClass *b1 = f.create("Descendant1");
BaseClass *b2 = f.create("Descendant2");
回答by mbrcknl
I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:
我大多同意已接受的答案,但现有答案中未涵盖 C++11 选项:
- Return factory method results by value, and
- Provide a cheap move constructor.
- 按值返回工厂方法结果,以及
- 提供廉价的移动构造函数。
Example:
例子:
struct sandwich {
// Factory methods.
static sandwich ham();
static sandwich spam();
// Move constructor.
sandwich(sandwich &&);
// etc.
};
Then you can construct objects on the stack:
然后就可以在栈上构造对象了:
sandwich mine{sandwich::ham()};
As subobjects of other things:
作为其他事物的子对象:
auto lunch = std::make_pair(sandwich::spam(), apple{});
Or dynamically allocated:
或者动态分配:
auto ptr = std::make_shared<sandwich>(sandwich::ham());
When might I use this?
我什么时候可以使用这个?
If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.
如果在公共构造函数上,没有一些初步计算就不可能为所有类成员提供有意义的初始化器,那么我可能会将该构造函数转换为静态方法。静态方法执行初步计算,然后通过私有构造函数返回值结果,该构造函数仅进行成员式初始化。
I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.
我说“可能”是因为它取决于哪种方法可以提供最清晰的代码,而不会造成不必要的低效。
回答by Jerry Coffin
Loki has both a Factory Methodand an Abstract Factory. Both are documented (extensively) in Modern C++ Design, by Andei Alexandrescu. The factory method is probably closer to what you seem to be after, though it's still a bit different (at least if memory serves, it requires you to register a type before the factory can create objects of that type).
Loki 有一个工厂方法和一个抽象工厂。Andei Alexandrescu在Modern C++ Design 中(广泛地)记录了两者。工厂方法可能更接近您所追求的,尽管它仍然有点不同(至少如果有记忆力,它要求您在工厂可以创建该类型的对象之前注册该类型)。
回答by Péter T?r?k
I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:
我不会试图回答我所有的问题,因为我认为它太宽泛了。只是一些注意事项:
there are cases when object construction is a task complex enough to justify its extraction to another class.
在某些情况下,对象构造是一项足够复杂的任务,足以证明其提取到另一个类是合理的。
That class is in fact a Builder, rather than a Factory.
该类实际上是一个Builder,而不是一个 Factory 。
In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.
在一般情况下,我不想强迫工厂的用户被约束到动态分配。
Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.
然后你可以让你的工厂把它封装在一个智能指针中。我相信这样你也可以吃蛋糕。
This also eliminates the issues related to return-by-value.
这也消除了与按价值回报相关的问题。
Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.
结论:通过返回对象来创建工厂确实是某些情况下的解决方案(例如前面提到的二维向量),但仍然不是构造函数的通用替代品。
Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.
的确。所有设计模式都有其(特定于语言的)约束和缺点。建议仅在它们帮助您解决问题时才使用它们,而不是为了它们本身。
If you are after the "perfect" factory implementation, well, good luck.
如果您追求“完美”的工厂实施,那么祝您好运。
回答by DAG
This is my c++11 style solution. parameter 'base' is for base class of all sub-classes. creators, are std::function objects to create sub-class instances, might be a binding to your sub-class' static member function 'create(some args)'. This maybe not perfect but works for me. And it is kinda 'general' solution.
这是我的 c++11 风格的解决方案。参数“base”用于所有子类的基类。创建者是用于创建子类实例的 std::function 对象,可能是对子类'静态成员函数'create(some args)'的绑定。这可能并不完美,但对我有用。这是一种“通用”解决方案。
template <class base, class... params> class factory {
public:
factory() {}
factory(const factory &) = delete;
factory &operator=(const factory &) = delete;
auto create(const std::string name, params... args) {
auto key = your_hash_func(name.c_str(), name.size());
return std::move(create(key, args...));
}
auto create(key_t key, params... args) {
std::unique_ptr<base> obj{creators_[key](args...)};
return obj;
}
void register_creator(const std::string name,
std::function<base *(params...)> &&creator) {
auto key = your_hash_func(name.c_str(), name.size());
creators_[key] = std::move(creator);
}
protected:
std::unordered_map<key_t, std::function<base *(params...)>> creators_;
};
An example on usage.
用法示例。
class base {
public:
base(int val) : val_(val) {}
virtual ~base() { std::cout << "base destroyed\n"; }
protected:
int val_ = 0;
};
class foo : public base {
public:
foo(int val) : base(val) { std::cout << "foo " << val << " \n"; }
static foo *create(int val) { return new foo(val); }
virtual ~foo() { std::cout << "foo destroyed\n"; }
};
class bar : public base {
public:
bar(int val) : base(val) { std::cout << "bar " << val << "\n"; }
static bar *create(int val) { return new bar(val); }
virtual ~bar() { std::cout << "bar destroyed\n"; }
};
int main() {
common::factory<base, int> factory;
auto foo_creator = std::bind(&foo::create, std::placeholders::_1);
auto bar_creator = std::bind(&bar::create, std::placeholders::_1);
factory.register_creator("foo", foo_creator);
factory.register_creator("bar", bar_creator);
{
auto foo_obj = std::move(factory.create("foo", 80));
foo_obj.reset();
}
{
auto bar_obj = std::move(factory.create("bar", 90));
bar_obj.reset();
}
}
回答by Matthieu M.
Factory Pattern
工厂模式
class Point
{
public:
static Point Cartesian(double x, double y);
private:
};
And if you compiler does not support Return Value Optimization, ditch it, it probably does not contain much optimization at all...
如果你的编译器不支持返回值优化,放弃它,它可能根本不包含太多优化......
回答by Florian Richoux
I know this question has been answered 3 years ago, but this may be what your were looking for.
我知道这个问题已经在 3 年前得到了回答,但这可能是您想要的。
Google has released a couple of weeks ago a library allowing easy and flexible dynamic object allocations. Here it is: http://google-opensource.blogspot.fr/2014/01/introducing-infact-library.html
谷歌几周前发布了一个库,允许简单灵活的动态对象分配。这是:http: //google-opensource.blogspot.fr/2014/01/introducing-infact-library.html