기본 콘텐츠로 건너뛰기

라벨이 CXX인 게시물 표시

Java 람다함수에서 외부지역변수를 수정할 수 없는 이유

 C++ 하다 보면, 람다함수에서 외부지역변수 수정을 숨쉬듯이 하는 편인데, Java 에서 동일한 형태로 람다함수를 사용하려고 하면, 오류난다. // Java import java.util.function.Consumer; public class MyClass { public String getString() { String result = ""; Consumer<String> lamda = (String name) -> { result = "<<" + name + ">>"; }; return result; } public static void main(String[] args) { System.out.println("new MyClass().getString(): " + new MyClass().getString()); } } // 컴파일 결과 // javac MyClass.java // MyClass.java:8: error: local variables referenced from a lambda expression must be final or effectively final // result = "<<" + name + ">>"; // ^ // 1 error // C++ #include <iostream> #include <string> using namespace std; class MyClass { public: string getString() { string result; auto lamda = [&] (stri...

기본 생성자가 없는 객체 배열을 만들 수 있나?

C++ in Action Book: Pointers There is no direct way to initialize the contents of a dynamically allocated array. We just have to iterate through the newly allocated array and set the values by hand. C++에서 new연산자를 이용해서 객체배열을 만들 때, 객체에 기본생성자는 없고 다른 생성자가 있을 경우는 사용할 수 있는 문법 자체가 전무하다. 그냥 처음부터 끝까지 돌면서 하나하나 초기화 해주시라는 답안이다. 잇힝~* C/C++이 상당히 유연하다고 생각했는데, 가끔씩 이런 것에서 뒷통수 때릴 수도 있다. 다른 언어는 어떨까? 왠지 Java/C#/D는 있을 것 같다. 원본 위치: http://purewell.egloos.com/4002582

delete this

[16] Freestore management, C++ FAQ Lite (내 맘대로 번역) [16.15] Is it legal (and moral) for a member function to say delete this? [16.15] 멤버함수에서 'delete this'가 올바른 구문인가? As long as you're careful, it's OK for an object to commit suicide (delete this). 주의 깊게 사용한다면, 객체가 자살하는 구문(delete this)은 괜찮다. Here's how I define "careful": 어떻게 "주의 깊게" 사용하냐면: You must be absolutely 100% positive sure that this object was allocated via new (not by new[], nor by placement new, nor a local object on the stack, nor a global, nor a member of another object; but by plain ordinary new). 이 객체는 new연산자(new[]도 아니고, new 오버라이딩도 아니고, 스택에 있는 지역 객체도 아니고, 전역 객체도 아니고, 다른 객체의 멤버변수도 아닌 순수 그 자체 new연산자 )로 만들어진다는 100% 확신이 있어야한다. You must be absolutely 100% positive sure that your member function will be the last member function invoked on this object. 'delete this'를 호출한 멤버함수는 이 객체에서 호출한 가장 마지막 멤버함수 라는 100% 확신이 있어야한다. You must be absolutely 100% positive sure that the rest of your ...