Programming/C++ STL2013. 2. 9. 21:56
에센셜 C++ 보다가 함수인자에서 포인터 변수가 아닌 이상한 녀석이 나타나서 순간 멘붕

int add(int *a, int *b) 가 c 스타일이라면
int add(int &a, int &b) 가 c++ 스타일(?)

무슨 차이인지는 일단 조사해 봐야겠지만, 문법의 유사함은 존재하지만 엄연히(!) c++ 용 문법인 듯.
내가 모르던건가? 내가 잘못쓴건가? 한 30분 고민했네 -_-

[링크 : http://www.learncpp.com/cpp-tutorial/73-passing-arguments-by-reference/]

---
[링크 : http://warmz.tistory.com/854] 생성/소멸자에 의한 오버헤드 테스트
[링크 : http://en.wikipedia.org/wiki/Evaluation_strategy]

'Programming > C++ STL' 카테고리의 다른 글

c++ template  (0) 2013.02.15
Essential C++  (0) 2013.02.14
C++ 첫걸음 *-_-*  (0) 2013.02.09
unsigned char -> int 변환 주의사항  (0) 2013.02.04
템플릿 메타프로그래밍  (0) 2013.01.06
Posted by 구차니
Programming/C++ STL2013. 2. 9. 19:19
학교에서 C++ 안하고
win32api랑 Java만 하고 졸업하고 MFC를 다뤄는 봤지만 C++을 생으로 해본적이 없어
저번달에는 Lisp 조금 해보고 이제 이번달에는 C++!ㅋㅋ

참조한 책은 Essential C++ (스탠리 B.립먼)

1. 책을 보다보니.. int a(0); 으로도 초기화가 된다고?!
#include <stdio.h>

void main()
{
        int a(0);
}

컴파일을 해보면 다른 소스라서 일단 제대로 되지 않으니 일단은 50%는 실패?
특이하게도 g++은 무조건 int main()으로 강제한다.

gcc test.c
test.c: In function ‘main’:
test.c:5:8: error: expected declaration specifiers or ‘...’ before numeric constant

g++ test.c
test.c:3:11: error: ‘::main’ must return ‘int’   
 
아래가 제대로 만든 c++ 소스. int a(0) 로도 초기화가 되는 신비함!!
(일단 a가 int형 객체일 경우 컨스트럭터로 인자를 하나 받아 초기화 해준다고 생각하면 간단하려나?)
#include <iostream>

int main()
{
        int a(0);

        return 0;
} 
 

2. cout 을 써봅시다 + long double 형?
c++에서는 .h를 제외하고 하는데 stdio 를 대체 하는 녀석은 바로 iostream!
#include <iostream>
//using namespace std;

int main()
{
        int a = 0;
        long double ld_t;

        cout << sizeof(ld_t) << '\n';

        return 0;
}

근데 cout이 안돼!!! 난 햄보칼수가 없엉 ㅠ.ㅠ

$ g++ test.c
test.c: In function ‘int main()’:
test.c:8:2: error: ‘cout’ was not declared in this scope
test.c:8:2: note: suggested alternative:
/usr/include/c++/4.6/iostream:62:18: note:   ‘std::cout’ 

cout의 경우에는 std::cout 으로 std에 포함된 cout 이기 때문에
굳이 저 소스로 하려면 std::cout << sizeof(ld_t) << '\n'; 으로 해야 한다.
그게 아니라면 간편하게 using namespace 를 이용해서 std를 기본으로 쓰도록 설정해준다. 

그리고 gcc 에서도 long double을 지원하기는 하는데.. 12byte 짜리(96bit ?!) 녀석이다. 

'Programming > C++ STL' 카테고리의 다른 글

Essential C++  (0) 2013.02.14
참조에 의한 전달(pass by reference)  (0) 2013.02.09
unsigned char -> int 변환 주의사항  (0) 2013.02.04
템플릿 메타프로그래밍  (0) 2013.01.06
c++ template  (0) 2012.05.12
Posted by 구차니
Programming/C++ STL2013. 2. 4. 23:31
원인은 대충 알고 있지만 해결책을 찾다 안되서 고민고민 -_-
아무튼 실험을 해보면, unsigned char 형에서 int로 암시적으로 형변환을 하면
결과쪽으로 형변환을 한것과 같아서 unsigned 형일 경우 의도하지 않은 형태로 값이 변형이 될 수 있다.

결론만 말하자면, unsigned 를 더 큰 크기의 signed로 저장할때 부호를 제대로 살리기 위해서는
작은 크기의 signed 형으로 변환하고(여기서는 unsigned char를 char 로) 넣어 주어야 한다 라는 점.

#include "stdio.h"

void main()
{
	unsigned char t1 = -1;
	char t2 = -1;
	int t3;

	t3 = t1;
	printf("%d\n",t3);

	t3 = (int)t1;
	printf("%d\n",t3);

	t3 = (char)t1;
	printf("%d\n",t3);

	t3 = t2;
	printf("%d\n",t3);

}

$ ./a.out
255
255
-1
-1 



---
원리적으로야
-1은 0x0FF에서 0x0000 00FF 으로 int로 확장시 앞에 채워지는 식으로 늘어 나는 바람에
의도한 값인 0xFFFF FFFF 가 되지 않아 부호가 상실하게 된다.

'Programming > C++ STL' 카테고리의 다른 글

참조에 의한 전달(pass by reference)  (0) 2013.02.09
C++ 첫걸음 *-_-*  (0) 2013.02.09
템플릿 메타프로그래밍  (0) 2013.01.06
c++ template  (0) 2012.05.12
리눅스에서 c++ 컴파일시 strcpy / strcat 오류  (0) 2011.10.13
Posted by 구차니
Programming/C++ STL2013. 1. 6. 23:28
템플릿을 이용하는건 제너릭 프로그래밍과 동일하지만
컴파일러에 조금더 의존을 해서, 최적화를 한다는데 자세한건 읽어봐야 할 듯

간략하게 한글 위키 내용을 요약하면,
factorial 같은 무거운 함수를 템플릿으로 작성하고
이걸 템플릿 메타 프로그래밍을 적용하면
factorial(N)에 대해서 컴파일러가 미리 처리해서
해당 값을 바로 리턴할수 있도록 컴파일 시간에 값을 정해버린다는 것.

엄청난 퍼포먼스 향상이 있을것으로 생각이 되지만...
컴파일러에 지극히 의존적이라 호환성이 떨어진다고 하니...

[링크 : http://ko.wikipedia.org/wiki/템플릿_메타프로그래밍]
[링크 : http://en.wikipedia.org/wiki/Template_metaprogramming]

[링크 : http://en.wikipedia.org/wiki/Generic_programming]

'Programming > C++ STL' 카테고리의 다른 글

C++ 첫걸음 *-_-*  (0) 2013.02.09
unsigned char -> int 변환 주의사항  (0) 2013.02.04
c++ template  (0) 2012.05.12
리눅스에서 c++ 컴파일시 strcpy / strcat 오류  (0) 2011.10.13
new / new[] / delete / delete[]  (4) 2010.09.16
Posted by 구차니
Programming/C++ STL2012. 5. 12. 10:45
C++ 템플렛 관련 정리가 잘되어 있는 링크 발견!

[링크 : http://ikpil.com/category/IT책%20정리실/C++%20Template# ]
Posted by 구차니
Programming/C++ STL2011. 10. 13. 22:12
두줄 넣으면 해결!

#include <cstring>
using namespace std;

[링크 : http://stackoverflow.com/questions/2220795/error-strcpy-was-not-declared-in-this-scope]

'Programming > C++ STL' 카테고리의 다른 글

템플릿 메타프로그래밍  (0) 2013.01.06
c++ template  (0) 2012.05.12
new / new[] / delete / delete[]  (4) 2010.09.16
cout 그리고 namespace  (0) 2010.09.16
C++ 레퍼런스 변수(reference variable)  (4) 2010.09.15
Posted by 구차니
Programming/C++ STL2010. 9. 16. 10:07
new와 delete,
new[] 와 delete[] 가 묶여야 한다고 한다.

즉,
 int *a = new int;
 delete a;

 int *arr = new int[10];
 delete[] arr; // delete arr[]; 이 아님

그렇다고 해서 링크드 리스트 처럼 다층으로 메모리를 할당하는 구조에서는
delete[] 가 자동으로 해주진 않는것으로 보인다.
(그냥 STL 쓰면 해결된다는 지인의 조언이 -_-)

[링크 : http://yesarang.tistory.com/39]

'Programming > C++ STL' 카테고리의 다른 글

c++ template  (0) 2012.05.12
리눅스에서 c++ 컴파일시 strcpy / strcat 오류  (0) 2011.10.13
cout 그리고 namespace  (0) 2010.09.16
C++ 레퍼런스 변수(reference variable)  (4) 2010.09.15
C++0x  (0) 2010.09.15
Posted by 구차니
Programming/C++ STL2010. 9. 16. 09:35
cout을 쓰려면
#include <iostream>
using namespace std;
두개를 써야 한다고 했는데, 문득 아래를 안쓰면 어떤 에러가 날지 궁금해졌다.

 error C2065: 'cout' : 선언되지 않은 식별자입니다.
음.. 역시 namespace가 다르니 인식을 하지 못하는 건가?

물론
std::cout << "Hello World";
라고 namespace를 직접 입력해주면 에러없이 실행이 가능하다.

[링크 : http://en.wikipedia.org/wiki/Namespace]

'Programming > C++ STL' 카테고리의 다른 글

리눅스에서 c++ 컴파일시 strcpy / strcat 오류  (0) 2011.10.13
new / new[] / delete / delete[]  (4) 2010.09.16
C++ 레퍼런스 변수(reference variable)  (4) 2010.09.15
C++0x  (0) 2010.09.15
std::vector 포인터  (0) 2010.09.13
Posted by 구차니
Programming/C++ STL2010. 9. 15. 13:06
int& a;
요 &가 바로 레퍼런스 변수이다.
어떻게 보면 포인터와 비슷하지만, 다른 녀석이고, C++ 공부중에 함수 인자에서 혼동을 느끼게 한 녀석이다.

// more than one returning value
#include <iostream>
using namespace std;

void prevnext (int x, int& prev, int& next)
{
  prev = x-1;
  next = x+1;
}

int main ()
{
  int x=100, y, z;
  prevnext (x, y, z);
  cout << "Previous=" << y << ", Next=" << z;
  return 0;
}

[링크 : http://www.cplusplus.com/doc/tutorial/functions2/]
[링크 : http://www.cplusplus.com/doc/tutorial/pointers/]

위의 소스중, prevent() 함수의 두/세번째 인자가 바로 reference 변수인데,
C에서는 당연히 포인터로 넘겨주어야 할꺼라고 생각을 했는데,
C++에서는 변수를 그냥 인자로 취해줌에도 불구하고 원본의 값이 바뀐다.
(당연히.. 레퍼런스 변수란걸 모르니 이상하게 보일수 밖에 ㅠ.ㅠ)

처음에는 자동형변환과 연관이 되어있나 했는데.. 그거랑은 거리가 좀 있는것 같고
그냥 단순히 C++ 문법적 특성으로 "참조형 변수" 라고 생각중 -_-

C++ 참조와 포인터의 차이점
- 만들어지면 값 변경불가
- 위의 이유로 null로 선언불가

C++ references differ from pointers in several essential ways:

  • It is not possible to refer directly to a reference object after it is defined; any occurrence of its name refers directly to the object it references.
  • Once a reference is created, it cannot be later made to reference another object; it cannot be reseated. This is often done with pointers.
  • References cannot be null, whereas pointers can; every reference refers to some object, although it may or may not be valid.
  • References cannot be uninitialized. Because it is impossible to reinitialize a reference, they must be initialized as soon as they are created. In particular, local and global variables must be initialized where they are defined, and references which are data members of class instances must be initialized in the initializer list of the class's constructor. For example:

[링크 : http://en.wikipedia.org/wiki/Reference_%28C%2B%2B%29]

[링크 : http://hijacker.egloos.com/1379523]
[링크 : http://www.cprogramming.com/tutorial/references.html]



'Programming > C++ STL' 카테고리의 다른 글

new / new[] / delete / delete[]  (4) 2010.09.16
cout 그리고 namespace  (0) 2010.09.16
C++0x  (0) 2010.09.15
std::vector 포인터  (0) 2010.09.13
스마트 포인터(smart pointer)  (2) 2010.09.09
Posted by 구차니
Programming/C++ STL2010. 9. 15. 10:19
C99 이런것들 처럼 C++에 대한 표준안이지만 현재로서는 비공식 표준이다.
친구로는
C++98 (1998년 제정 표준)
C++03 (2003년 제정 표준)이 있다.
[링크 : http://en.wikipedia.org/wiki/C%2B%2B98#Language_standard]

[링크 : http://ko.wikipedia.org/wiki/C%2B%2B0x]
[링크 : http://en.wikipedia.org/wiki/C%2B%2B0x]

'Programming > C++ STL' 카테고리의 다른 글

cout 그리고 namespace  (0) 2010.09.16
C++ 레퍼런스 변수(reference variable)  (4) 2010.09.15
std::vector 포인터  (0) 2010.09.13
스마트 포인터(smart pointer)  (2) 2010.09.09
C++ 강좌/문법/reference  (4) 2010.09.09
Posted by 구차니