gpt4 book ai didi

c++ - 如果对象具有私有(private)复制构造函数,为什么我不能初始化对象数组?

转载 作者:行者123 更新时间:2023-11-30 04:21:24 24 4
gpt4 key购买 nike

我刚刚在处理 C++ 项目时遇到了一些意外且令人沮丧的行为。我的实际代码稍微复杂一些,但下面的示例同样捕获了它:

class Irritating
{
public: Irritating() {}
private: Irritating(const Irritating& other) {}
};

const Irritating singleton; // Works just fine.
const Irritating array[] = {Irritating()}; // Compilation error.

int main()
{
return 0;
}

尝试编译它会产生以下错误(以防万一抛出 GCC 版本):

[holt@Michaela irritating]$ g++ --version
g++ (GCC) 4.6.3 20120306 (Red Hat 4.6.3-2)
Copyright (C) 2011 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

[holt@Michaela irritating]$ g++ test.cpp
test.cpp:4:11: error: ‘Irritating::Irritating(const Irritating&)’ is private
test.cpp:8:41: error: within this context
[holt@Michaela irritating]$

不幸的是,有问题的对象来自外部库并且在我的控制范围之外。我目前的解决方法是使用指针数组;它有效,但感觉有点老套,并增加了一个不必要的间接层。有更好的方法吗?

此外:数组是常量和全局的(好吧,在实际代码中是类静态的);为什么不在适当的地方初始化它?这是预期的 C++ 行为,还是 GCC 的错误/怪癖?

更新:安装 Clang 只是为了看看它是否与 GCC 一致。可悲的是,它做到了:

[holt@Michaela irritating]$ clang test.cpp
test.cpp:8:29: warning: C++98 requires an accessible copy constructor for class 'Irritating' when binding a reference to a temporary; was private
[-Wbind-to-temporary-copy]
const Irritating array[] = {Irritating()};
^
test.cpp:4:11: note: declared private here
private: Irritating(const Irritating& other) {}
^
test.cpp:8:29: error: calling a private constructor of class 'Irritating'
const Irritating array[] = {Irritating()};
^
test.cpp:4:11: note: declared private here
private: Irritating(const Irritating& other) {}
^
1 warning and 1 error generated.
[holt@Michaela irritating]$

最佳答案

因为单个数组元素是通过复制初始化从通过 = {...} 语法指定的初始化器初始化的。参见 8.5/12 (C++03)

The initialization that occurs in argument passing, function return, throwing an exception (15.1), handling an exception (15.3), and brace-enclosed initializer lists (8.5.1) is called copy-initialization

复制初始化需要复制构造函数(即使它实际上不会使用它)。

实际上,如果您通过公开复制构造函数来编译代码,编译器可能会在不使用复制构造函数的情况下就地初始化您的数组元素。然而,抽象语言的形式规则要求在这种情况下进行复制初始化。

关于c++ - 如果对象具有私有(private)复制构造函数,为什么我不能初始化对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14543554/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com