I have defined class A as follows.
#include <cstring>
#include <utility>
class A
{
private:
int *pa_;
std::size_t size_;
public:
explicit A(std::size_t size)
: pa_{new int[size]}, size_{size} {};
// copy constructor
A(const A &other)
: pa_{new int[other.size_]}, size_{other.size_}
{
std::memcpy(pa_, other.pa_, size_);
}
// move constructor
A(A &&other)
: pa_{other.pa_}, size_{other.size_}
{
other.pa_ = nullptr;
}
};
I have tried several copy/move constructor calls.
int main(int argc, char const *argv[])
{
A a1{100}; // ok
A(a1); // error
A a2 = A(a1); // ok
A{a1}; // ok
A aa[] = { // ok
A(a1),
A(a1)};
A(std::move(a1)); // ok
}
The following error occurs.
> g++-11 -std=c++17 -Wall -pedantic-errors -fdiagnostics-color=always example.cpp
example.cpp: In function 'int main(int, const char**)':
example.cpp:30:4: warning: unnecessary parentheses in declaration of 'a1' [-Wparentheses]
30 | A(a1); // error
| ^~~~
example.cpp:30:4: note: remove parentheses
30 | A(a1); // error
| ^~~~
| - -
example.cpp:30:5: error: redeclaration of 'A a1'
30 | A(a1); // error
| ^~
example.cpp:29:5: note: 'A a1' previously declared here
29 | A a1{100}; // ok
| ^~
example.cpp:33:5: warning: unused variable 'aa' [-Wunused-variable]
33 | A aa[] = { // ok
| ^~
Why does a copy constructor call using parentheses result in a compile error?
Is this a problem that cannot be solved?
I don't know if I actually need to use this syntax, but the behavior is counter-intuitive.