这是一个简单的、独立的、不可在 gcc-4.8.2 上编译的示例,说明了我想要完成的任务:
#include <atomic>
template <typename T>
class ValueParameter
{
public:
ValueParameter() = default;
ValueParameter(T initialValue) :
_val(initialValue)
{
}
private:
std::atomic<T> _val{T()};
};
ValueParameter<int> x;
我已经在其他几个 gcc 版本(包括 5.3)上成功编译了此代码,但 gcc 4.8.2 失败并出现以下错误:
/tmp/gcc-explorer-compiler11658-82-1cqz6ui/example.cpp: In constructor 'ValueParameter<T>::ValueParameter() [with T = int]':
7 : error: use of deleted function 'std::atomic<int>::atomic(const std::atomic<int>&)'
ValueParameter() = default;
^
In file included from /tmp/gcc-explorer-compiler11658-82-1cqz6ui/example.cpp:1:0:
You can see the results online here .
据我了解std::atomic<T>
是不可复制的,但对我来说,为什么编译器会尝试在默认构造函数中使用复制构造函数没有任何意义。我确实发现改变线路:
std::atomic<T> _val{T()};
至
std::atomic<T> _val;
使文件编译成功。统一初始化是该类的早期版本的遗留物,该版本没有采用初始值的构造函数。
这应该是一个错误吗?此外,在这种情况下,我应该期望什么行为,其中成员是在类内联和构造函数初始值设定项列表中初始化的?我希望默认构造函数初始化 val
至T()
,所以我想我需要那里的大括号初始值设定项。
最佳答案
这绝对是一个 gcc 错误,他们已在 4.9 中修复了该错误。您的代码绝不会调用 ValueParameter<T>
的复制构造函数- 因此不应实例化成员函数。使用 atomic<T>
的默认成员初始值设定项很好 - 它确实可以从 T
构造出来。 .
Furthermore, what behavior should I expect in this case, where the member is initialized both inline to the class and within a constructor initializer list?
默认成员初始值设定项就是默认值。如果您在 mem-initializer-list 中提供了初始值设定项(如在 ValueParameter(T )
构造函数中所做的那样),则默认值将被忽略。如果您不提供这样的初始值设定项(如 ValueParameter()
中所示),则使用默认值。
I would like the default constructor to initialize val to
T()
, so I think I need the brace initializer there.
您的代码应该准确地执行您希望它执行的操作。 gcc 4.8 只是这里有一个错误。
关于c++ - gcc 4.8.2 在此默认的默认构造函数中调用复制构造函数是否正确?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707129/