[]를 사용할 때 C ++ 맵 유형 인수에 빈 생성자가 필요한 이유는 무엇입니까?
중요한 문제는 아니지만 특정 인수없이 클래스가 인스턴스화되는 것을 원하지 않기 때문에 성가시다.
#include <map>
struct MyClass
{
MyClass(int t);
};
int main() {
std::map<int, MyClass> myMap;
myMap[14] = MyClass(42);
}
이것은 다음과 같은 g ++ 오류를 제공합니다.
/usr/include/c++/4.3/bits/stl_map.h:419 : 오류 : 'MyClass ()'호출에 일치하는 함수가 없습니다.
기본 생성자를 추가하면 잘 컴파일됩니다. 잘못된 구문으로 인한 것이 아니라고 확신합니다.
이 문제는 operator []와 함께 발생합니다. SGI 문서에서 인용 :
data_type& operator[](const key_type& k)
-특정 키와 관련된 개체에 대한 참조를 반환합니다. 지도에 이러한 객체가 아직 포함되지 않은 경우operator[]
기본 객체를 삽입합니다data_type()
.
기본 생성자가없는 경우 삽입 / 찾기 함수를 사용할 수 있습니다. 다음 예제는 잘 작동합니다.
myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) );
myMap.find( 1 )->second;
예. STL 컨테이너의 값은 복사 의미 체계를 유지해야합니다. IOW, 기본 유형 (예 : int)처럼 동작해야합니다. 즉, 무엇보다도 기본 구성이 가능해야합니다.
이 (및 기타 요구 사항) 없이는 STL 컨테이너가 구현되는 데이터 구조에서 다양한 내부 복사 / 이동 / 스왑 / 비교 작업을 구현하기가 불필요하게 어려울 것입니다.
C ++ 표준을 참조하면 내 대답이 정확하지 않다는 것을 알 수 있습니다. 기본 구성은 실제로 요구 사항이 아닙니다 .
20.1.4.1부터 :
기본 생성자는 필요하지 않습니다. 특정 컨테이너 클래스 멤버 함수 서명은 기본 생성자를 기본 인수로 지정합니다. T ()는 잘 정의 된 표현식이어야합니다 ...
따라서 엄밀히 말해서 값 유형은 서명에서 기본 생성자를 사용하는 컨테이너의 함수를 사용하는 경우에만 기본 구성 가능해야합니다.
STL 컨테이너에 저장된 모든 값의 실제 요구 사항 (23.1.3)은 CopyConstructible
및 Assignable
.
특정 컨테이너에 대한 기타 특정 요구 사항도 있습니다 Comparable
(예 : 맵의 키).
덧붙여서, 다음은 comeau에서 오류없이 컴파일됩니다 .
#include <map>
class MyClass
{
public:
MyClass(int t);
};
int main()
{
std::map<int, MyClass> myMap;
}
따라서 이것은 g ++ 문제 일 수 있습니다.
Check requirements of stored type of the stl::map. Many stl collection require that stored type contains some specific properties (default constructor, copy constructor, etc.).
Constructor without arguments is needed by the stl::map, because it's used, when operator[] is invoked with the key, which hasn't already been kept by the map. In this case the operator[] inserts the new entry consisting of the new key and value constructed using parameterless constructor. And this new value is then returned.
Check if:
- You forgot the ';' after class declaration.
- MyType should've been declared accordingly.
- No default constructor there...
The std::map declaration seems correct, I think.
Most likely because std::pair requires it. std::pair holds two values using value semantics so you need to be able to instantiate them without parameters. So the code uses std::pair in various places to return the map values to the caller and this is commonly done by instantiating an empty pair and assigning the values into it before returning the local pair.
You could get around this with smart pointers using a map<int, smartptr<MyClass> > but that adds the overhead of checking for null pointers.
'program tip' 카테고리의 다른 글
TypeScript 인터페이스에서 정적 속성을 정의하는 방법 (0) | 2020.09.12 |
---|---|
Pandas 데이터 프레임 열 dtypes 할당 (0) | 2020.09.12 |
When, if ever, is loop unrolling still useful? (0) | 2020.09.12 |
How to get the name of a function in Go? (0) | 2020.09.12 |
Java에서 Ordered Set 구현이 있습니까? (0) | 2020.09.12 |