草庐IT

C++11奇怪的大括号初始化行为

coder 2023-05-31 原文

我不明白 C++11 大括号初始化规则在这里是如何工作的。 拥有此代码:

struct Position_pod {
    int x,y,z;
};

class Position {
public:
    Position(int x=0, int y=0, int z=0):x(x),y(y),z(z){}
    int x,y,z;
};

struct text_descriptor {
    int             id;
    Position_pod    pos;
    const int       &constNum;
};

struct text_descriptor td[3] = {
     {0, {465,223}, 123},
     {1, {465,262}, 123},
};

int main() 
{
    return 0;
}

注意,数组被声明为有 3 个元素,但只提供了 2 个初始化器。

但是它编译没有错误,这听起来很奇怪,因为最后一个数组元素的引用成员将未初始化。确实,它有 NULL 值:

(gdb) p td[2].constNum 
$2 = (const int &) @0x0: <error reading variable>

现在是“魔法”:我将 Position_pod 更改为 Position

struct text_descriptor {
    int             id;
    Position_pod    pos;
    const int       &constNum;
};

变成这样:

struct text_descriptor {
    int             id;
    Position        pos;
    const int       &constNum;
};

现在它给出了预期的错误:

error: uninitialized const member ‘text_descriptor::constNum'

我的问题:为什么它在第一种情况下编译,什么时候应该给出错误(如在第二种情况下)。 不同的是,Position_pod 使用 C 风格的大括号初始化,而 Position 使用 C++11 风格的初始化,调用 Position 的构造函数。但这会如何影响不初始化引用成员的可能性呢?

(更新) 编译器: gcc (Ubuntu 4.8.2-19ubuntu1) 4.8.2

最佳答案

很明显

struct text_descriptor td[3] = {
     {0, {465,223}, 123},
     {1, {465,262}, 123},
};

是列表初始化,并且初始化列表不为空。

C++11 说 ([dcl.init.list]p3):

List-initialization of an object or reference of type T is defined as follows:

  • If the initializer list has no elements and T is a class type with a default constructor, the object is value-initialized.
  • Otherwise, if T is an aggregate, aggregate initialization is performed (8.5.1).
  • ...

[dcl.init.aggr]p1:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

td是数组,所以是聚合,所以进行聚合初始化。

[dcl.init.aggr]p7:

If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from an empty initializer list (8.5.4).

这里就是这种情况,所以 td[2] 是从一个空的初始化列表初始化的,这(再次是 [dcl.init.list]p3)意味着它是值初始化的。

反过来,值初始化意味着 ([dcl.init]p7):

To value-initialize an object of type T means:

  • if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), ...
  • if T is a (possibly cv-qualified) non-union class type without a user-provided constructor, then the object is zero-initialized and, if T's implicitly-declared default constructor is non-trivial, that constructor is called.
  • ...

你的类 text_descriptor 是一个没有用户提供构造函数的类,所以 td[2] 首先是零初始化,然后调用它的构造函数。

零初始化意味着([dcl.init]p5):

To zero-initialize an object or reference of type T means:

  • if T is a scalar type (3.9), ...
  • if T is a (possibly cv-qualified) non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits;
  • if T is a (possibly cv-qualified) union type, ...
  • if T is an array type, ...
  • if T is a reference type, no initialization is performed.

无论 text_descriptor 的默认构造函数如何,这都是明确定义的:它只是将非引用成员和子成员初始化为零。

然后调用默认构造函数,如果它是非平凡的。下面是默认构造函数的定义方式([special]p5):

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4). An implicitly-declared default constructor is an inline public member of its class. A defaulted default constructor for class X is defined as deleted if:

  • ...
  • any non-static data member with no brace-or-equal-initializer is of reference type,
  • ...

A default constructor is trivial if it is not user-provided and if:

  • its class has no virtual functions (10.3) and no virtual base classes (10.1), and
  • no non-static data member of its class has a brace-or-equal-initializer, and
  • all the direct base classes of its class have trivial default constructors, and
  • for all the non-static data members of its class that are of class type (or array thereof), each such class has a trivial default constructor.

Otherwise, the default constructor is non-trivial.

因此,隐式定义的构造函数被删除,正如预期的那样,但是如果 pos 是 POD 类型(!),它也是微不足道的。因为构造函数是微不足道的,所以它没有被调用。因为构造函数没有被调用,所以被删除是没有问题的。

这是 C++11 中的一个大漏洞,现已修复。碰巧已经修复处理inaccessible trivial default constructors ,但固定的措辞也涵盖已删除的琐碎默认构造函数。 N4140(大约 C++14)在 [dcl.init.aggr]p7(强调我的)中说:

  • if T is a (possibly cv-qualified) class type without a user-provided or deleted default constructor, then the object is zero-initialized and the semantic constraints for default-initialization are checked, and if T has a non-trivial default constructor, the object is default-initialized;

作为 T.C.在评论中指出,another DR也进行了更改,以便 td[2] 仍然从一个空的初始化程序列表进行初始化,但是该空的初始化程序列表现在意味着聚合初始化。反过来,这意味着 td[2] 的每个成员也是从一个空的初始化程序列表初始化的(再次是 [dcl.init.aggr]p7),所以似乎初始化了引用{} 的成员。

[dcl.init.aggr]p9 然后说(正如 remyabel 在现已删除的答案中指出的那样):

If an incomplete or empty initializer-list leaves a member of reference type uninitialized, the program is ill-formed.

我不清楚这是否适用于从隐式 {} 初始化的引用,但编译器确实会这样解释它,而且它没有太多其他含义。

关于C++11奇怪的大括号初始化行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28408911/

有关C++11奇怪的大括号初始化行为的更多相关文章

  1. ruby-on-rails - 未初始化的常量 Psych::Syck (NameError) - 2

    在我的gem中,我需要yaml并且在我的本地计算机上运行良好。但是在将我的gem推送到ruby​​gems.org之后,当我尝试使用我的gem时,我收到一条错误消息=>"uninitializedconstantPsych::Syck(NameError)"谁能帮我解决这个问题?附言RubyVersion=>ruby1.9.2,GemVersion=>1.6.2,Bundlerversion=>1.0.15 最佳答案 经过几个小时的研究,我发现=>“YAML使用未维护的Syck库,而Psych使用现代的LibYAML”因此,为了解决

  2. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  3. ruby-on-rails - 未在 Ruby 中初始化的对象 - 2

    我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调

  4. ruby - 如何根据特征实现 FactoryGirl 的条件行为 - 2

    我有一个用户工厂。我希望默认情况下确认用户。但是鉴于unconfirmed特征,我不希望它们被确认。虽然我有一个基于实现细节而不是抽象的工作实现,但我想知道如何正确地做到这一点。factory:userdoafter(:create)do|user,evaluator|#unwantedimplementationdetailshereunlessFactoryGirl.factories[:user].defined_traits.map(&:name).include?(:unconfirmed)user.confirm!endendtrait:unconfirmeddoenden

  5. ruby-on-rails - ActionController::RoutingError: 未初始化常量 Api::V1::ApiController - 2

    我有用于控制用户任务的Rails5API项目,我有以下错误,但并非总是针对相同的Controller和路由。ActionController::RoutingError:uninitializedconstantApi::V1::ApiController我向您描述了一些我的项目,以更详细地解释错误。应用结构路线scopemodule:'api'donamespace:v1do#=>Loginroutesscopemodule:'login'domatch'login',to:'sessions#login',as:'login',via::postend#=>Teamroutessc

  6. ruby - 这两个 Ruby 类初始化定义有什么区别? - 2

    我正在阅读一本关于Ruby的书,作者在编写类初始化定义时使用的形式与他在本书前几节中使用的形式略有不同。它看起来像这样:classTicketattr_accessor:venue,:datedefinitialize(venue,date)self.venue=venueself.date=dateendend在本书的前几节中,它的定义如下:classTicketattr_accessor:venue,:datedefinitialize(venue,date)@venue=venue@date=dateendend在第一个示例中使用setter方法与在第二个示例中使用实例变量之间是

  7. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  8. ruby - 安装libv8(3.11.8.13)出错,Bundler无法继续 - 2

    运行bundleinstall后出现此错误:Gem::Package::FormatError:nometadatafoundin/Users/jeanosorio/.rvm/gems/ruby-1.9.3-p286/cache/libv8-3.11.8.13-x86_64-darwin-12.gemAnerroroccurredwhileinstallinglibv8(3.11.8.13),andBundlercannotcontinue.Makesurethat`geminstalllibv8-v'3.11.8.13'`succeedsbeforebundling.我试试gemin

  9. ruby - Ruby gsub 替换中的行为不一致? - 2

    两个gsub产生不同的结果。谁能解释一下为什么?代码也可在https://gist.github.com/franklsf95/6c0f8938f28706b5644d获得.ver=9999str="\tCFBundleDevelopmentRegion\n\ten\n\tCFBundleVersion\n\t0.1.190\n\tAppID\n\t000000000000000"putsstr.gsub/(CFBundleVersion\n\t.*\.).*()/,"#{$1}#{ver}#{$2}"puts'--------'putsstr.gsub/(CFBundleVersio

  10. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

随机推荐