单例模式:auto_ptr和unique_ptr的不同行为

Mas*_*ano 5 c++ linker singleton static auto-ptr

在实现工厂类时,我遇到了std::auto_ptr一些我无法理解的行为.我将问题减少到下面的小程序,所以......让我们开始吧.

考虑以下单例类:

singleton.h

#ifndef SINGLETON_H_
#define SINGLETON_H_

#include<iostream>
#include<memory>

class singleton {
public:
  static singleton* get() {
    std::cout << "singleton::get()" << std::endl;
    if ( !ptr_.get() ) {
      std::cout << &ptr_ << std::endl;
      ptr_.reset( new singleton  );
      std::cout << "CREATED" << std::endl;
    }
    return ptr_.get();
  }

  ~singleton(){
    std::cout << "DELETED" << std::endl;
  }
private:
  singleton() {}
  singleton(const singleton&){}

  static std::auto_ptr< singleton > ptr_;
  //static std::unique_ptr< singleton > ptr_;
};

#endif
Run Code Online (Sandbox Code Playgroud)

singleton.cpp

#include<singleton.h>o
std::auto_ptr< singleton > singleton::ptr_(0);
//std::unique_ptr< singleton > singleton::ptr_;
Run Code Online (Sandbox Code Playgroud)

这里使用智能指针来管理资源主要取决于在程序退出时避免泄漏的需要.我在以下程序中使用此代码:

#ifndef A_H_
#define A_H_

int foo();

#endif
Run Code Online (Sandbox Code Playgroud)

a.cpp

#include<singleton.h>

namespace {
  singleton * dummy( singleton::get() );
}

int foo() {  
  singleton * pt = singleton::get();
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#include<a.h>

int main() {

  int a = foo();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

现在有趣的部分.我分别编译了三个来源:

$ g++  -I./ singleton.cpp -c 
$ g++  -I./ a.cpp -c 
$ g++  -I./ main.cpp -c
Run Code Online (Sandbox Code Playgroud)

如果我按此顺序显式链接它们:

$ g++ main.o singleton.o a.o
Run Code Online (Sandbox Code Playgroud)

一切都按照我的预期工作,我得到以下内容到stdout:

singleton::get()
0x804a0d4
CREATED
singleton::get()
DELETED
Run Code Online (Sandbox Code Playgroud)

相反,我使用此顺序链接源:

$ g++ a.o main.o singleton.o
Run Code Online (Sandbox Code Playgroud)

我得到这个输出:

singleton::get()
0x804a0dc
CREATED
singleton::get()
0x804a0dc
CREATED
DELETED
Run Code Online (Sandbox Code Playgroud)

我尝试了不同的编译器品牌(Intel和GNU)和版本,这种行为在它们之间是一致的.无论如何,我无法看到其行为取决于链接顺序的代码.

此外,如果auto_ptrunique_ptr行为代替,总是与我期望的正确一致.

这让我想到了一个问题:有没有人知道这里发生了什么?

Yak*_*ont 4

dummystd::auto_ptr< singleton > singleton::ptr_(0)的构造顺序未指定。

对于这种auto_ptr情况,如果您构造dummythen singleton::ptr_(0),则调用中创建的值dummy将被 的构造函数删除ptr_(0)

ptr_我会在过孔ptr_(([](){ std::cout << "made ptr_\n"; }(),0));或类似的构造中添加跟踪。

它使用的事实unique_ptr是巧合的,并且可能是由于优化unique_ptr(0)可以确定它被归零,因此什么也不做(static数据在构造开始之前被归零,所以如果编译器能够弄清楚unique_ptr(0)只是将内存归零,它可以合法地跳过构造函数,这意味着您不再将内存归零)。

解决这个问题的一种方法是使用保证先构建后使用的方法,例如:

   static std::auto_ptr< singleton >& get_ptr() {
     static std::auto_ptr< singleton > ptr_(0);
     return ptr_;
   }
Run Code Online (Sandbox Code Playgroud)

ptr_并将对的引用替换为get_ptr().