开发者

std::vector and Constructors

Which constructor does std::vector call when it is making a new instance of the object it's containing? I am under the impression it calls a default constructor but what if one is not defined or is the compiler doing that for me?开发者_如何学运维

Particularly in a case as such:

class Foo
{
    public:
        Foo(int size)
        {
            data = new double[size];
        }


        ~Foo()
        {
            delete[] data;
        }

    private:
        double* data;
};

std::vector<Foo> myVector;
Foo bar(5);
myVector.push_back(bar);
//stuff

How does it know how much memory to allocate when the object has an unknown size until after construction?


At a minimum, for std::vector<T> to compile, T must be copy-constructible, and copy-assignable. If you want to use std::vector<T>::vector(int) (or std::vector<T>::resize()), then T must have be default-constructible. If any of these requirements are not fulfilled, the code will not compile.

...

C++03 standard, section 23.1 (discussing containers in general):

The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.

Section 20.1.4:

20.1.4 Default construction

The default constructor is not required. Certain container class member function signatures specify the default constructor as a default argument. T() shall be a well-defined expression (8.5) if one of those signatures is called using the default argument (8.3.6).


What happens, after you fix the error:

std::vector<Foo> myVector;
myVector.reserve(10);
myVector.push_back(bar);

is that you have two Foo instances pointing to the same data buffer. It will probably appear to work for a while, but eventually both objects get destroyed, the destructor is called twice (or more, depending on whether the vector needs to move its content around) and the buffer is double-freed, resulting in undefined behavior (which usually means crash).


To address the initial content of the vector, it copy-constructs the pattern you pass in as a parameter (this parameter defaults to a default-constructed object, but doesn't have to be):

std::vector<Foo> myVector(10, bar); // 10 copies of bar
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜