llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

Clang choosing copy constructor over initializer_list

Open lkattha opened this issue 4 years ago • 6 comments

The following short program returns '3' with clang, but '30' with GCC and '12' with MSVC. The issue is that in lines (3) and (4), both the copy-constructor (1) and the initializer_list constructor (2) could be called. According to cppreference.com, (2) should be called. However, clang chooses (1) on both instances. (Interestingly, MSVC chooses (2) on (3) and (1) on (4).

This error also accurs if the constructor of S takes an initializer_list of another type T, which can be implicitly contructed from S, this is how I encountered the bug in real code.

#include <initializer_list>

struct S {
    S() = default;
    S(const S& other): i_(1) {} // (1)
    S(const std::initializer_list<S> args): i_(10) {} // (2)

    int i_;
};

struct T {
    //Clang: calls (1)
    //GCC, MSVC: calls (2)
    T(const S& s) : s_{s} {}       // (3)

    S s_;
};

int main() {
    S s;
    T t(s);

    //Clang, MSVC: calls  (1)
    //GCC: calls (2)
    S s2{s};        // (4)

    return t.s_.i_ + 2*s2.i_;
}

lkattha avatar Oct 21 '22 08:10 lkattha

@llvm/issue-subscribers-clang-frontend

llvmbot avatar Oct 21 '22 13:10 llvmbot

This looks like DR 2137 which reverted the change from DR 1467 which is the behavior that we are currently implementing AFAICT.

The clang defect report status indicates we implemented 1467 but we have unknown status for 2137 (presumedly b/c we did not implement it).

shafik avatar Oct 21 '22 20:10 shafik

@llvm/issue-subscribers-c-1

llvmbot avatar Oct 21 '22 20:10 llvmbot

i'd like to know if anyone started working on DR2137! @shafik @AaronBallman

Long5hot avatar Aug 09 '23 11:08 Long5hot

i'd like to know if anyone started working on DR2137! @shafik @AaronBallman

There is a recent in-progress patch up for review at https://reviews.llvm.org/D156032

AaronBallman avatar Aug 09 '23 13:08 AaronBallman

Duplicate of #24186.

zygoloid avatar Jan 09 '24 19:01 zygoloid