[英]Passing new object as default argument to constructor
I have a constructor which looks like: 我有一个看起来像的构造函数:
RandomClass(const int16_t var1, const SecondClass& var2);
I need to pass a default argument to the second parameter, so currently I do something like this: 我需要将默认参数传递给第二个参数,因此目前我正在执行以下操作:
RandomClass(const int16_t var1, const SecondClass& var2 = *(new SecondClass(*(new std::unordered_map<int16_t, double>())));
which is incredibly awkward. 真是尴尬 Note that I do not want to use an overloaded constructor, or change the second parameter from a reference to a pointer. 请注意,我不想使用重载的构造函数,也不想将第二个参数从引用更改为指针。
What would an elegant way of passing the default parameter be? 传递默认参数的一种优雅方式是什么?
You are allowed to bind a const reference to a temporary: 您可以将const引用绑定到临时目录:
RandomClass(const int16_t var1, const SecondClass& var2 = SecondClass(std::unordered_map<int16_t, double>()));
Of course this assumes that you either copy var2
into a member or do not use it after the constructor exits. 当然,这假定您将var2
复制到成员中,或者在构造函数退出后不使用它。 If this is not the case, then something is wrong in your design. 如果不是这种情况,则说明您的设计有问题。 Perhaps using a raw pointer or a shared/weak_ptr
is more appropriate. 也许使用原始指针或shared/weak_ptr
更合适。
The way to do this nicely is to provide two overloads for your constructor: 很好地做到这一点的方法是为构造函数提供两个重载:
RandomClass(const int16_t var1, const SecondClass& var2)
{
// ...
}
RandomClass(const int16_t var1)
{
const SecondClass var2 = *(new SecondClass(*(new std::unordered_map<int16_t, double>()));
}
However, you have a much worse problem than how it looks. 但是,您遇到的问题要比看起来的糟糕得多。 What you have in that second overload is incredibly horrendous because it results in memory leaks - you need to delete
everything you new
but now you've lost any trace of what you new
ed. 第二次过载中的内容令人难以置信,因为这会导致内存泄漏-您需要delete
所有new
但现在您丢失了所有new
痕迹。 You would simply do this: 您只需执行以下操作:
RandomClass(const int16_t var1)
{
const SecondClass var2{std::unordered_map<int16_t, double>()};
}
Don't use new
unless you have to - prefer automatic storage duration. 不要使用new
偏好自动存储时间-除非你要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.