3

I don't understand why C++ seems to suppress generation of defaulted ctors in an explicit template instance. For this source file,

template<class VAL>
class C
{
public:
  C() = default
  C(C const&) = default;
  C(VAL const val) : val_(val) {}

private:
  VAL val_ = 42;

};

template class C<int>;

the object file includes the explicit ctor but no the defaulted default and copy ctors.

$ c++ -std=c++14 ctorinst.cc -c
$ nm ctorinst.o | c++filt
0000000000000000 W C<int>::C(int)
0000000000000000 W C<int>::C(int)
0000000000000000 n C<int>::C(int)

If, however, I write out these two ctors myself,

public:
  C() {}
  C(C const& c) : val_(c.val_) {}

they appear in the object file.

$ c++ -std=c++14 ctorinst2.cc -c
$ nm ctorinst2.o | c++filt
0000000000000000 W C<int>::C(int)
0000000000000000 W C<int>::C(C<int> const&)
0000000000000000 W C<int>::C()
0000000000000000 W C<int>::C(int)
0000000000000000 W C<int>::C(C<int> const&)
0000000000000000 W C<int>::C()
0000000000000000 n C<int>::C(int)
0000000000000000 n C<int>::C(C<int> const&)
0000000000000000 n C<int>::C()

Tested on gcc 5.3.1 (Linux) and clang-700.1.81 (OS/X). Why is this?

  • 1
    I think they are only generated if your code use it – qPCR4vir May 30 '16 at 15:24
  • Also, default constructors are prime candidates for automatic inlining. – md5i May 30 '16 at 16:13
  • @qPCR4vir, @md5i: All these methods are great candidates for inlining, and (implicitly) marked `inline` by virtue of being defined within the class body. My understanding is that the explicit instantiation (the last line) is supposed to force generation of all members of the template instance, whether or not each is used, inline or out of line. – Alex Samuel Jun 04 '16 at 14:31

0 Answers0