Comments (9)
struct S { std::string a, b; }; std::vector<S> v; v.push_back({"abc", "xyz"}); // ↓の方が好ましい(ことが多い) v.emplace_back("abc", "xyz");
『ゼロから学ぶC++』はC++11を対象としているので, emplace_back
だと集成体初期化は行えない(上記コードの v.emplace_back("abc", "xyz")
はコンパイルエラーになる )ため, push_back
の方が簡潔に記述できる,ということはあると思います.
struct S { std::string a, b; };
std::vector<S> v;
v.push_back({"abc", "xyz"}); // compiles
v.emplace_back("abc", "xyz"); // fails to compile
v.emplace_back({"abc", "xyz"}); // fails to compile
v.emplace_back(S{"abc", "xyz"}); // compiles
from cpp-book.
ところでClangで下のコード通らないのなんででしょう・・・
StackOverflow回答 Does clang++ 12 support C++20 std::construct_at? によれば、単に未実装のようです。
from cpp-book.
まあ全部のケースでpush_backを置き換えられるわけではないというのはたしかにそうですね。
どう修正しましょうか・・・。
例えば 書籍 Effective Modern C++ では「項目42:要素の挿入の代わりに直接配置を検討する」と紹介されていますね。
push_back
/emplace_back
の最適な使い分けまで考えるとサイト趣旨を超えてしまうため、高度なトピックとして紹介するにとどめる程度が現実解かなと思います。
素案:
C++11より前は push_back という関数のみが末尾への要素追加を担っていました。 C++11で追加された emplace_back は要素型のコンストラクタに直接引数を渡すことができるので push_back と同じかそれ以上のパフォーマンスを得られるケースがあります。両者の最適な使い分けは高度なトピックとなるため、詳細は 書籍 Effective Modern C++ で紹介される「項目42:要素の挿入の代わりに直接配置を検討する」を参照ください。
from cpp-book.
本件に関して、StackOverflow上の議論 Why would I ever use push_back instead of emplace_back? がありました。
暗黙(implicit)/明示(explicit)コンストラクタの違いにフォーカスした例示があげられています。
std::vector<std::unique_ptr<T>> v;
T a;
v.emplace_back(std::addressof(a)); // compiles
v.push_back(std::addressof(a)); // fails to compile
かなりマニアックなケースであることは否めませんが、「すべてのpush_back
はemplace_back
で代替すべき」の反例として挙げておきます。
from cpp-book.
まあ全部のケースでpush_backを置き換えられるわけではないというのはたしかにそうですね。どう修正しましょうか・・・。
ところでClangで下のコード通らないのなんででしょう・・・
#include <string>
#include <vector>
int main()
{
struct S { std::string a, b; };
std::vector<S> v;
v.push_back({"abc", "xyz"}); // compiles
v.emplace_back("abc", "xyz"); // fails to compile
//v.emplace_back({"abc", "xyz"}); // fails to compile
v.emplace_back(S{"abc", "xyz"}); // compiles
}
https://wandbox.org/permlink/hmwRtwbKIC8NPC9b
In file included from prog.cc:1:
In file included from /opt/wandbox/clang-head/include/c++/v1/string:506:
In file included from /opt/wandbox/clang-head/include/c++/v1/string_view:175:
In file included from /opt/wandbox/clang-head/include/c++/v1/__string:57:
In file included from /opt/wandbox/clang-head/include/c++/v1/algorithm:643:
/opt/wandbox/clang-head/include/c++/v1/memory:1600:17: error: no matching function for call to 'construct_at'
_VSTD::construct_at(__p, _VSTD::forward<_Args>(__args)...);
^~~~~~~~~~~~~~~~~~~
/opt/wandbox/clang-head/include/c++/v1/__config:828:15: note: expanded from macro '_VSTD'
#define _VSTD std::_LIBCPP_ABI_NAMESPACE
^
/opt/wandbox/clang-head/include/c++/v1/memory:1442:14: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<S>>::__construct<S, char const (&)[4], char const (&)[4]>' requested here
{__construct(__has_construct<allocator_type, _Tp*, _Args...>(),
^
/opt/wandbox/clang-head/include/c++/v1/vector:926:21: note: in instantiation of function template specialization 'std::__1::allocator_traits<std::__1::allocator<S>>::construct<S, char const (&)[4], char const (&)[4]>' requested here
__alloc_traits::construct(this->__alloc(), _VSTD::__to_address(__tx.__pos_),
^
/opt/wandbox/clang-head/include/c++/v1/vector:1687:9: note: in instantiation of function template specialization 'std::__1::vector<S, std::__1::allocator<S>>::__construct_one_at_end<char const (&)[4], char const (&)[4]>' requested here
__construct_one_at_end(_VSTD::forward<_Args>(__args)...);
^
prog.cc:10:7: note: in instantiation of function template specialization 'std::__1::vector<S, std::__1::allocator<S>>::emplace_back<char const (&)[4], char const (&)[4]>' requested here
v.emplace_back("abc", "xyz"); // fails to compile
^
/opt/wandbox/clang-head/include/c++/v1/memory:903:16: note: candidate template ignored: substitution failure [with _Tp = S, _Args = <char const (&)[4], char const (&)[4]>]: no matching constructor for initialization of 'S'
constexpr _Tp* construct_at(_Tp* __location, _Args&& ...__args) {
^
1 error generated.
from cpp-book.
Clang,ちょいちょいC++20サポートが貧弱なので…
from cpp-book.
うーん、自分はまずemplace_back
を使ってみてエラーになったらpush_back
という使い方をしてきたんですが、それじゃだめですかね
from cpp-book.
emplace_back
を使ってみてエラーになったらpush_back
という使い方
改めて書籍 Effective Modern C++(日本語版) の記載を確認してみましたが、yumetodo さん方針では セキュアコーディング の観点から不安が残ります。
前掲のStackOverflow回答にも言及ありますが、push_back
にくらべてemplace_back
は 強力な機能 です。
セマンティクス上はコンパイルエラーとなるべき(例えばpush_back
であればコンパイル時に検出できる問題)ケースでもemplace_back
ではコンストラクトできてしまい、実行時に発生する未定義動作により困難なデバッグ作業を強いられる可能性を否めません。以下、書籍よりサンプルを引用します。
#include <vector>
#include <regex>
int main()
{
std::vector<std::regex> rv;
rv.emplace_back(nullptr); // 実行時エラー
// rv.push_back(nullptr); // コンパイルエラー
}
from cpp-book.
セキュアコーディング の観点
なるほど、そこには頭が回っていなかったですね・・・。
from cpp-book.
Related Issues (20)
- 結局関数オブジェクトとはなんなのか HOT 6
- std::functionのメリット/デメリットとは HOT 4
- char は signed char でも unsigned char でもない HOT 4
- ポインタはイテレータでもある HOT 1
- inline指定された変数(C++17)どう説明するか HOT 2
- new/deleteの再考 HOT 1
- 構造体は存在しない HOT 2
- エラー処理: errnoやstd::error_code(C++11)やstd::optional(C++17)をどう考えるか
- switch の条件 HOT 1
- 範囲for文の挙動 HOT 2
- pointer interconvertible HOT 1
- アクセス指定子の説明の違和感
- [proposal][dev]netlifyの導入
- override キーワードの効果 HOT 1
- 用語:メンバ変数
- 配列の要素数 HOT 2
- 「7.12 共用体」と「9.3 特殊化」におけるtypo
- 3.1. 配列 中の誤記について HOT 3
- ダークモード対応 HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from cpp-book.