C++ class static variable 초기화

freezm7의 이미지

class A
{
static B;
}

이런 코드가 있을 때,
init(&B) 라는 코드를 단 한번만 실행하고 싶은데,
초기화 되었음을 나타내는 플래그 같은 것을 써도 되겠지만,

클래스 변수를 초기화 하는데 쓰이는
문법이 없을까요?

doldori의 이미지

static으로 선언한 자체로 한 번만 초기화되는데요.
다른 특별한 일을 하고 싶으신 건지요?

yielding의 이미지

class A {
public:
   static int b;
};
int A::b = 10;

스태틱 변수는 위의 경우처럼 explicit하게 초기화를 해야합니다. 선언자체로 초기화되지 않습니다.

Life rushes on, we are distracted

doldori의 이미지

yielding wrote:
스태틱 변수는 위의 경우처럼 explicit하게 초기화를 해야합니다. 선언자체로 초기화되지 않습니다.

물론입니다. "static으로 선언한 멤버를 적절하게 정의했다고 가정할 때"
한 번만 초기화된다는 뜻이었습니다.
cdpark의 이미지

static 변수를 바로 노출시키지 말고, singleton 패턴으로 감싸는 건 어떨까요?

Fe.head의 이미지

cdpark wrote:
static 변수를 바로 노출시키지 말고, singleton 패턴으로 감싸는 건 어떨까요?

음..이뜻은 무엇인지..

제가 궁금해서요.
아래처럼 코딩 하면 되나요?..

class A
{
  static int a;
};

class singleton_A
{
  A  *_pa;
public:
  A * instance_A()
  {
       if(pa == NULL)
        {
               _pa = new A;
               int A::a = 0;         //?? 맞나요?
         }
       return _pa;
  }
   singleton_A() : _pa(NULL) {}
};

위의것이 맞나요?..
뭔가 이상이 있는것 같은데..

고작 블로킹 하나, 고작 25점 중에 1점, 고작 부활동
"만약 그 순간이 온다면 그때가 네가 배구에 빠지는 순간이야"

litdream의 이미지

위의 코드는 한단계 더 거쳐서 singleton 을 쓰는데,
저는 대략 다음과 같은 싱글톤을 씁니다.

#include <iostream>
using namespace std;

class A {
public:
   static A* Instance();
   int  getData()     { return data; }
   void increment()   { data++; }
private:
   A() { data=0; }
   static A* _instance;
   int data;
};

A* A::_instance = NULL;
A* A::Instance() {
   if ( _instance == NULL ) {
      _instance = new A;
   }
   return _instance;
}

int main() {
   A *single = A::Instance();
   cout << single->getData() << endl;
   single->increment();
   cout << single->getData() << endl;

   A *another = A::Instance();
   cout << another->getData() << endl;

   delete(single);
   return 0;
}

테스트 코드를 보시면 아시겠지만,
인스턴스는 하나밖에 만들어지지 않습니다.
data 는 private 으로 보호되고요.

삽질의 대마왕...

cdpark의 이미지

delete(single)은 꽤 위험해보이는군요.

만약 다른 곳에서 singleton 패턴을 쓰고 있다거나, 삭제 후에 다시 singleton 패턴을 호출할 일이 생기면...

Fe.head의 이미지

그러면 소멸자에서 해제 해야되나요?..

고작 블로킹 하나, 고작 25점 중에 1점, 고작 부활동
"만약 그 순간이 온다면 그때가 네가 배구에 빠지는 순간이야"

gimmesilver의 이미지

fehead wrote:
그러면 소멸자에서 해제 해야되나요?..

리소스 해제용 함수를 따로 만드시고 레퍼런스 카운팅을 하셔야 겠죠...

------------------------
http://agbird.egloos.com

litdream의 이미지

테스트 코드라서, 버릇상 main 마지막에서 delete 를 써버렸네요.. singleton 을 해재하지 않는다는 말씀에 동의합니다~

삽질의 대마왕...

yielding의 이미지

말 나온김에 andrei alexsandrescu의 modern c++ design에 소개된 singleton까지 공부한다면 좋겠군요. complete라 말할 수는 없지만 하나를 제대로 안다는게 참 여럽다는걸 확실하게 느끼게 해줍니다.

Life rushes on, we are distracted

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.