I have this class template defined in test.hpp
:
#pragma once
extern void Foo();
template <typename F>
class MyClass {
public:
void Compute() {
Foo();
}
};
And a function test()
instantiate MyClass
in test.cpp
:
#include "test.hpp"
void test() {
MyClass<int> a;
a.Compute();
}
If compiled with clang++ test.cpp -S -emit-llvm
, MyClass<int>
and MyClass<int>::Compute()
are kept in generated ll file.
6 %class.MyClass = type { i8 }
7 ; Function Attrs: noinline optnone ssp uwtable
8 define void @_Z4testv() #0 {
9 %1 = alloca %class.MyClass, align 1
10 call void @_ZN7MyClassIiE7ComputeEv(%class.MyClass* %1)
11 ret void
12 }
13 ; Function Attrs: noinline optnone ssp uwtable
14 define linkonce_odr void @_ZN7MyClassIiE7ComputeEv(%class.MyClass* %0) #0 align 2 {
15 %2 = alloca %class.MyClass*, align 8
16 store %class.MyClass* %0, %class.MyClass** %2, align 8
17 %3 = load %class.MyClass*, %class.MyClass** %2, align 8
18 call void @_Z3Foov()
19 ret void
20 }
But for O2 compilation, MyClass<int>::Compute()
is inlined and deleted, together with the MyClass<int>
definition. For some reason, I want them kept in the generated file, like in O0. So my question is that is there a way to keep them not deleted? I'd expect a simple attribute on the class or the member function.
----Edit----
The reason I want to keep the class is because I need to register it into a framework. That framework will find its 'Compute' method and call it on demand. I thought it may fail the framework if the class definition is deleted. But in my real senario, 'MyClass' needs to be derived from a base class provided by the framework, and 'Compute' is a virtual function that 'MyClass' needs to override. On registering this class, I must provide a builder which returns a pointer of base class, pointing to 'MyClass' (like template <typename F> BaseClass *Builder() { return new MyClass<F>{}; }
. And with all these present, the compiler won't delete 'MyClass'. When I was asking this question, I was trying to implement this derived class as a template class in a header file, and thought it might be a little bit different than a regular class implemented in cpp file that the framework usually expect. It turns out not that special. So I guess my question is not a good question. Thanks for all the comments and answers, still help me a lot, thanks.
question from:
https://stackoverflow.com/questions/65860737/how-to-prevent-inlined-class-template-from-being-deleted-by-compiler 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…