PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] Why does the C++ standard library always pass std::initializer_list<T> by value rather than by reference?

 July 06, 2022     c++, c++11, pass-by-reference, pass-by-value, standards     No comments   

Issue

As a C++ programmer, I have been taught the simple rule of passing parameters:

Passing parameter T by value when sizeof(T) <= sizeof(void*) or for constructing in-place and move in.

However, the C++ standard library seems not comply with the rule. For example, sizeof(std::initializer_list<T>) is greater than sizeof(void*), but std::vector has a constructor:

vector(std::initializer_list<T>, const Allocator&);

Why does the C++ standard library always pass std::initializer_list<T> by value rather than by reference?


Solution

From cppreference on initializer_list:

The lifetime of the underlying array is the same as any other temporary object, except that initializing an initializer_list object from the array extends the lifetime of the array exactly like binding a reference to a temporary (with the same exceptions, such as for initializing a non-static class member).

So initializer_list already acts like a reference to a temporary.

The idea behind initializer_list is to move the data from temporaries or copy it from read-only memory directly to the destination container. It is not a container per se.



Answered By - Alex Guteniev
Answer Checked By - Timothy Miller (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing