void Add(const Test& t)
{
m_vec.push_back(t);
}
private:
vector<Test> m_vec;
};
This compiles just fine using Microsoft's (or should I say
Dinkumware's) STL in VS2008 but fails on STLPort 5.1.5 with same
compiler. Does C++ standard say something about this?
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]
While inside the declaration of a class T, T is an incomplete type,
and STL containers are not allowed to hold incomplete types or the
result is undefined behavior. Thus, your code contains undefined
behavior. In general, a stl container that is a member of a class
cannot hold elements of that containing class's type. You may,
however, hold pointers to that type, or preferably, smart pointers
like boost::shared_ptr, which is designed to work with incomplete
types.
--
Chris
Yes, the standard [17.4.3.6] says it is undefined behaviour to
instantiate a template component with an incomplete type. So a
conforming implementation can pretty much do what it wants, including
rejecting the code.
DP
> class Test
> {
> public:
>
> void Add(const Test& t)
> {
> m_vec.push_back(t);
> }
>
> private:
>
> vector<Test> m_vec;
> };
>
> This compiles just fine using Microsoft's (or should I say
> Dinkumware's) STL in VS2008 but fails on STLPort 5.1.5 with same
> compiler. Does C++ standard say something about this?
Yes. Template type parameters used to instantiare standard library
containers such as std::vector<> are required to be complete. Otherwise the
behavior is undefined. [17.4.3.6/2]
In particular, the effects are undefined in the following cases:
[...]
? if an incomplete type (3.9) is used as a template argument when
instantiating a template component.
Best
Kai-Uwe Bux
Which is very unfortunate, because one can easily implement
vector that allows instantiating with incomplete types and it
won't add any overhead.
Roman Perepelitsa.
> class Test
> {
> public:
>
> void Add(const Test& t)
> {
> m_vec.push_back(t);
>
> }
>
> private:
>
> vector<Test> m_vec;
>
> };
>
> This compiles just fine using Microsoft's (or should I say
> Dinkumware's) STL in VS2008 but fails on STLPort 5.1.5 with same
> compiler. Does C++ standard say something about this?
Speaking technically, it will work as expected because std::vector<>
has no members of type T, rather T* (Test* in this case).
As others have replied, the standard explicitly prohibits
instantiating any standard templates with incomplete types. To learn
the full story please see "Containers of Incomplete Types" by Matthew
H. Austern. http://www.ddj.com/database/184403814
Max