为什么以下代码会生成这样的输出?
main.cpp ctor 0x24a4c30
test.cpp dtor 0x24a4c30
测试.cpp
#include <boost/optional.hpp>
struct Test
{
Test()
{
printf("test.cpp ctor %p\n", (void *) this);
}
~Test()
{
printf("test.cpp dtor %p\n", (void *) this);
}
};
boost::optional< Test > t;
主文件
#include <memory>
struct Test
{
Test()
{
printf("main.cpp ctor %p\n", (void *) this);
}
~Test()
{
printf("main.cpp dtor %p\n", (void *) this);
}
};
int
main(void)
{
std::make_shared< Test >();
return 0;
}
编译
g++ -std=c++11 -c test.cpp -o test.o
g++ -std=c++11 -c main.cpp -o main.o
g++ -std=c++11 test.o main.o
我解释了test.o提供 Test 的ctor & dtor然后链接器丢弃来自main.o的重复符号的这种行为,但它仅适用于dtor。如果我删除静态对象t那么链接器会丢弃test.o中的符号,输出是下一个
main.cpp ctor 0x208ec30
main.cpp dtor 0x208ec30