初始化禁止复制的成员类

我有一个成员变量,它是一个禁止复制的类(删除了复制赋值运算符)。我想进行一些检查以确定将成员初始化为什么,因此我需要在构造函数中而不是在初始化列表中执行此操作。在进入 MyClass 的构造函数之前,成员变量 m 似乎已经用默认构造函数进行了初始化,那么构造函数的意义何在……对不起,c++ 咆哮。

简单的例子:

class MyClass {
    NonCopy m;
    MyClass() {
        // Complex checks
        if(success) {
            m("success");
        else {
            m("failure");
        }

    }

我看到的选项是:

  • 驻留在m的动态分配
  • 放宽复印禁止要求

回答

只要该类具有有效的复制或移动构造函数,或者您使用的是 C++17+,您就可以创建一个执行逻辑的辅助函数,然后返回正确的对象。然后使用它来初始化您的成员。那看起来像

class MyClass {
    NonCopy m;
    static NonCopy initialize_noncopy()
    {
        // Complex checks
        if(success) {
            return NonCopy("success");
        else {
            return NonCopy("faulure");
        }
    }
public:
    MyClass() : m(initialize_noncopy()) { }
};

  • @AyxanHaqverdili Depends. If you can't use C++17, or the class doesn't have a copy/move c'tor, then yes, that might be the way to go. I try to avoid it though and try to put that logic into named functions. Also, while the check in the example code is simple, the comment says *Complex checks* which most likely means in the OP's real code, a simple check like that might not be enough. Hence, I show this approach.

以上是初始化禁止复制的成员类的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>