【问题标题】:How to use ExplicitInit class from Objective-C sources?如何使用来自 Objective-C 源代码的 ExplicitInit 类?
【发布时间】:2022-08-14 19:54:03
【问题描述】:

在 Objc 源代码中,我找到了以下代码。这段代码是什么意思,如何理解?

objc/项目标头/DenseMapExtras.h 行:38

template <typename Type>
class ExplicitInit {
    alignas(Type) uint8_t _storage[sizeof(Type)];

public:
    template <typename... Ts>
    void init(Ts &&... Args) {
        new (_storage) Type(std::forward<Ts>(Args)...);
    }

    Type &get() {
        return *reinterpret_cast<Type *>(_storage);
    }
};

下面是我的测试代码:

class MyC{
public:
    long l1;
    long l2;
    MyC(long _l1, long _l2){
        l1 = _l1;
        l2 = _l2;
    }
};
int main(){
    MyExplicitInit<MyC> e1 {};
    e1.init();
    return 0;
}

编译器提示如下错误:

  • 这段代码是什么意思,如何理解?-- C++ 是最难学的语言之一。你不能通过挑选你在某处找到的代码并试图理解它来学习它。你对转发参数了解多少?安置新的?结盟?如果不首先了解 C++ 超出初学者阶段,您将不会得到答案(无论如何,最好的 C++ 书籍可以回答)。
  • 更简单。这里应该如何填写参数?
  • @Crazs 请参阅good c++ book

标签: c++ ios objective-c


【解决方案1】:

在 Objc 源代码中,我找到了以下代码。是什么 这段代码的含义以及如何理解它?

对我来说,它看起来像是一种工厂,可以用来替代构造第一次使用成语.这里的实例化类代表一个实例的存储,您可以在需要时初始化和请求。据我了解,它不应该用于局部变量(尽管在技术上可行,但它没有多大意义),这也是suggested by the comments of code section with the said class template

// We cannot use a C++ static initializer to initialize certain globals because
// libc calls us before our C++ initializers run. We also don't want a global
// pointer to some globals because of the extra indirection.
//
// ExplicitInit / LazyInit wrap doing it the hard way

对于您遇到的错误:

非分配放置新表达式没有匹配的operator new 函数; 包括&lt;new&gt;

假设您刚刚在自己的源代码中添加了那段代码,这里的问题是您没有包含 &lt;new&gt; 标头。就这么简单-错误只是说您需要添加#include &lt;new&gt;,因为所谓的安置新不是“默认”C++ 的一部分,它是一个重载运算符declared in this header

其次,您的 init 函数需要与给定类的现有(非聚合)构造函数之一匹配的参数,因此您应该传递与构造函数参数匹配或可以隐式转换为它们的参数:@987654329 @

一个完整的示例如下所示:

#include <_types/_uint8_t.h>
#include <new>

namespace objc {

    template <typename Type>
    class ExplicitInit {
        alignas(Type) uint8_t _storage[sizeof(Type)];

    public:
        template <typename... Ts>
        void init(Ts &&... Args) {
            new (_storage) Type(std::forward<Ts>(Args)...);
        }

        Type &get() {
            return *reinterpret_cast<Type *>(_storage);
        }
    };

};

struct sample_struct {
    long l1, l2;
    
    sample_struct(long _l1, long _l2): l1{_l1}, l2{_l2} {}
};

sample_struct& getInstance(bool should_init = false) {
    static objc::ExplicitInit<sample_struct> factory;
    if (should_init) {
        factory.init(1l, 2l);
    }
    return factory.get();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-28
    • 1970-01-01
    • 2017-09-08
    相关资源
    最近更新 更多