Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of function parameter initialized by list initialization

Could anyone help me with the following problem?

There is a simple code:

#include <vector>

struct A {
    std::vector<int> vec;
};

void func (A &&a = {}) {}

int main()
{
    func();
    return 0;
}

When I try to compile it by gcc 5.4.0 I get the error:

undefined reference to `std::vector<int, std::allocator<int> >::vector()'

Amazingly, but clang compiles it well. Also if to modify the code a little bit it is compiled without any problems:

#include <vector>

struct A {
    std::vector<int> vec;
};

void func (A &&a) {}

int main()
{
    func({});
    return 0;
}

I really cann't understand what's wrong with the first code.

like image 272
Алексей Шалашов Avatar asked Jun 16 '17 11:06

Алексей Шалашов


People also ask

What is default value parameter function?

Default function parameters allow named parameters to be initialized with default values if no value or undefined is passed.

What type of parameter can be given a default value?

Default Parameter Data TypesAny primitive value or object can be used as a default parameter value.

Which operator is used to initialize value for default arguments?

Of the operators, only the function call operator and the operator new can have default arguments when they are overloaded. You can supply any default argument values in the function declaration or in the definition.

What is default parameter in Python?

Default values indicate that the function argument will take that value if no argument value is passed during the function call. The default value is assigned by using the assignment(=) operator of the form keywordname=value.


1 Answers

This is a gcc bug. It can also be reproduced with

template<typename Value>
struct A
{
    A() = default;
    std::vector<Value> m_content;
};

void func(A<int> a = {})
{
}

int main()
{
    func();
}

Currently though, there is no status on it.

I appears that the lack of an actual instance of the vector is causing the compiler to not stamp out the code for it which leads to the undefined reference.

like image 57
NathanOliver Avatar answered Sep 25 '22 22:09

NathanOliver