Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GNU C++ can not create vector of constant custom class instances

I have a very simple demo program that compiles well on Microsoft Visual C++:

#include <cstdio>
#include <vector>
#include <string>

using namespace std;

class String
    :public wstring
{
public:
    String(void)
    {
    }

    String(const String &other)
        : wstring(other)
    {
    }
};

int main(void)
{
    vector<const String> v;
    v.push_back(String());
    printf("Hello, World!");
    return 0;
}

It creates vector of constant strings. However, in GNU C++ 4.8.2 it gives a lot of errors that try to say that it is impossible to create vector of constant String objects. When I replace vector<const String> with vector<String>, it compiles. What is the reason of such GNU C++ behavior?

like image 943
Vitalii Avatar asked Dec 08 '25 22:12

Vitalii


1 Answers

std::vector deals with instances of your class in a specific way in regards to memory management. Some of operations it performs on data require copy constructor and assignment operator or a noexcept move constructor/assignment operator. GCC is quite correct not to compile your example which doesn't have any of these. const T cannot be a valid type for a std::vector.

like image 172
4pie0 Avatar answered Dec 11 '25 10:12

4pie0



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!