내 선호도는 항상 const
회원보다 더 많은 커플 링을 생성하는 것처럼 보일 수 있으므로 static const
회원을 사용하면 안됩니다. 때로는 혼란 스럽다.final 클래스가 2 개의 수퍼 클래스 (1 클래스는 상속 됨 public
에서 상속 받음)에서 상속받은 최종 상속 계층은 new
, malloc
, calloc
등을 통해 동적 메모리 영역을 가리키는 static const
멤버를 정의하면 double free
이됩니다. 오류.
여기에 간단한 다이아몬드 상속 상황 여기
ray:~ ray$ ./multiinheritance
Base() called
Derived1() called
Base() called
Derived2() called
Final() called
~Final() called
~Derived2() called
~Base() called
freeing memory
~Derived1() called
~Base() called
freeing memory
multiinheritance(475) malloc: *** error for object 0x100150: double free
*** set a breakpoint in malloc_error_break to debug
ray:~ ray$
의 출력 코드 것입니다 작성자 :
#include <iostream>
#include <string>
class Base {
public:
Base() {
std::cout << "Base() called " << std::endl;
}
virtual ~Base() {
std::cout << "~Base() called" << std::endl;
std::cout << "freeing memory" << std::endl;
delete i;
}
static const int* i;
};
const int* Base::i = new int[5];
class Derived1 : virtual public Base {
public:
Derived1() {
std::cout << "Derived1() called " << std::endl;
}
virtual ~Derived1() {
std::cout << "~Derived1() called" << std::endl;
}
};
class Derived2 : public Base {
public:
Derived2() {
std::cout << "Derived2() called " << std::endl;
}
virtual ~Derived2() {
std::cout << "~Derived2() called" << std::endl;
}
};
class Final: public Derived1, public Derived2 {
public:
Final() {
std::cout << "Final() called" << std::endl;
}
~Final() {
std::cout << "~Final() called" << std::endl;
}
};
int main(int argc, char** argv) {
Final f;
return 0;
}
는 "변경되지 않습니다"나는 값이 클래스의 모든 객체에 대해 동일 의미했다. – trikker
그런 경우에는'static const'를하지 않을 이유가 없습니다. 정적이 아닌 const는 (특정/이국적인 경우를 제외하고) 잘 작동하지만 불필요하게 낭비되는 메모리 낭비를 초래합니다. – AnT
네, 그게 제가 가진 요점입니다. – trikker