开发者

Will a class recall its constructor when pushed in a std::vector?

if for example I do:

FOO foo;
foovect.push_back(foo);

where FOO is a class with a default constructor.

Will the constructor be called only when foo is put on the stack, or is it called again开发者_如何学JAVA when pushed into the std::vector?

Thanks

I'm doing:

OGLSHAPE::OGLSHAPE(void)
{
    glGenBuffersARB(GL_ARRAY_BUFFER_ARB,&ObjectVBOInt);

}


FOO foo; would call the constructor.
foovect.push_back(foo); would call the copy constructor.

#include <iostream>
#include <vector>

class FOO
{
public:
    FOO()
    {
        std::cout << "Constructor" << std::endl;
    }
    FOO(const FOO& _f)
    {
        std::cout << "Copy Constructor" << std::endl;
    }
};

int main()
{
    FOO foo;
    std::vector<FOO> foovect;
    foovect.push_back(foo);
}

Output for this:
Constructor
Copy Constructor


No, the copy constructor is used, i.e. the one that looks like this:

FOO( const FOO & f );

A default copy constructor is provided by the compiler, if you don't provide one yourself.


When you do a push_back, your object is copied into the vector. That means the copy constructor for your object gets called. All the standard library containers deal with copies of objects, not the object themselves. If you want that behavior, you'll need to resort to using pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜