初始化禁止复制的成员类 [英] Initialize member class that prohibits copy
问题描述
我有一个成员变量,该成员变量是禁止复制的类(删除了复制赋值运算符).我想进行一些检查以确定将成员初始化为什么,因此我需要在构造函数中而不是在初始化列表中进行此操作.似乎成员变量m在进入MyClass的构造函数之前已经使用默认的构造函数进行了初始化,那么该构造函数的意义是什么...对不起c ++ rant.
I have a member variable that is a class that prohibits copying (copy assignment operator is deleted). I want to make some checks to determine what to initiate the member to, thus I need to do this inside the constructor and not in and initializer list. It seem the member variable m is already initialed with the default constructor before entering the constructor of MyClass, then what is the point of the constructor... sorry for c++ rant.
简单的例子:
class MyClass {
NonCopy m;
MyClass() {
// Complex checks
if(success) {
m("success");
else {
m("failure");
}
}
我看到的选项是:
- 依赖于m的动态分配
- 禁止复制m的要求
推荐答案
只要该类具有有效的副本或move构造函数,或者您正在使用C ++ 17 +,就可以创建一个执行逻辑的辅助函数.然后返回正确的对象.然后,您可以使用它来初始化您的成员.看起来像
As long as the class has a valid copy or move constructor, or you are using C++17+, you can make a helper function that does the logic and then returns the correct object. You then use that to initialize your member. That would look like
class MyClass {
NonCopy m;
static NonCopy initialize_noncopy()
{
// Complex checks
if(success) {
return NonCopy("success");
else {
return NonCopy("faulure");
}
}
public:
MyClass() : m(initialize_noncopy()) { }
};
这篇关于初始化禁止复制的成员类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!