c++11 - C++ Weird behavior on vector of pair containing reference -


i've found weird, check out code:

#include <cstring> #include <cstdio> #include <utility> #include <vector>  using namespace std;  class {     public:     int n = 0;     a(const char* p) { n = strlen(p); };      a(a const&) = delete;     void operator=(a const&) = delete; }; void f(vector<pair<const char*, const a&>> v) {     printf("f\n");     for(vector<pair<const char*, const a&>>::iterator = v.begin();it!=v.end();++it) printf("  '%s': %p %i\n", it->first, &it->second, it->second.n); };  int main(int, char**) {     f({             { "a", "a" },             { "b", "bb" },             { "c", "ccc" },             { "d", "dddd" }         }); }; 

now compile clang++ -std=c++11 -wall -wextra -wpedantic -o0 main.cc -o main, or similar (with optimization disabled).

and should see output this:

f   'a': 0x7fff57a0b988 1   'b': 0x7fff57a0b9d0 2   'c': 0x7fff57a0ba18 3   'd': 0x7fff57a0ba60 4 

which nice, compiler automatically creates vector object , corresponding a& references, different.

now, compile clang++ -std=c++11 -wall -wextra -wpedantic -o1 main.cc -o main, notice how added lowest level of optimization.

and see,

f   'a': 0x7fff5ac54b30 1629262454   'b': 0x7fff5ac54b30 1629262454   'c': 0x7fff5ac54b30 1629262454   'd': 0x7fff5ac54b30 1629262454 

that parameters reference same a& object, find wrong.

here compiler details:

apple llvm version 6.0 (clang-600.0.57) (based on llvm 3.5svn) target: x86_64-apple-darwin14.1.0 thread model: posix 

is expected behavior? compiler bug?

update: pointed out matt mcnabb, vectors , initializer_lists not designed work const references (although, compiles fine in clang). however, when writing same function void f(vector<pair<char*, a&&>>) {} error still persists.

your code seems bit odd. you're doing this:

void f(vector<pair<const char*, const a&>> v) { 

so you're expecting vector references a objects. don't have objects. you're passing string literals, compiler implicitly creates objects - temporary, time function body runs, gone, , referencing them undefined behavior, why works -o0, not -o1.

if want implicitly create a objects , keep them, can't use references. try

void f(vector<pair<const char*, const a>> v) { 

example here: http://ideone.com/vnigal


Comments

Popular posts from this blog

python - pip install -U PySide error -

arrays - C++ error: a brace-enclosed initializer is not allowed here before ‘{’ token -

cytoscape.js - How to add nodes to Dagre layout with Cytoscape -