Conditional Link Assignment

Can anyone with a deeper understanding of the C ++ standard than me, comment on this?

This is my sample program.

#include <string>
#include <iostream>

int main(int argc, char* argv[]) {
    const std::string message("hello world");
    std::cout << std::hex << (void*)message.c_str() << std::endl;
    const std::string& toPrint = (argc > 0) ? message : "";
    std::cout << std::hex << (void*)toPrint.c_str() << std::endl;
    return 0;
}

On one machine, he does this:

# g++ --version && g++ str_test.cpp && ./a.out                  
g++ (Debian 4.7.2-5) 4.7.2
Copyright (C) 2012 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.

0x9851014
0x9851014

messageand toPrintseem to refer to the same instance that I would expect. However, on another machine, this happens:

# g++ --version && g++ str_test.cpp && ./a.out 
g++ (Ubuntu 5.2.1-22ubuntu2) 5.2.1 20151010
Copyright (C) 2015 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.

0x7ffeb9ab4ac0
0x7ffeb9ab4ae0

Here, it looks like the compiler built a copy messagefor toPrintto point to.

Which behavior is correct according to the C ++ standard? Or is it generally undefined?

+4
source share
2 answers
Martin Bonner explains why the address may be the same even for a copy of the string.

To explain why it is message and toPrint seem to refer to the same instance as I would expect.wrong, I will give a standard.

, ( , , ). . void.

[expr.cond]/3 , (, cv-qualit) , glvalues ​​ , cv -qualification, . , E1 T1 E2 T2 :

  • E2 - lvalue: E1 E2, E1 "lvalue reference to T2", , lvalue. ( lvalue std::string )
  • E2 - x: E1 E2, E1 "rvalue reference to T2", , . ( x)
  • E2 rvalue , (, cv-qualit) :
    • E1 E2 , : E1 E2, T2 , T1, cv- T2 cv-, cv-, cv- T1. , E1 prvalue T2 - T2 E1 . ( )
    • (.. E1 E2 , , ): E1 E2, E1 , E2, E2 prvalue ( , , E2 - prvalue). ( )

. nonclass std::string prvalue.

, .

4 glvalues ​​ ( ), , -, , .

5 prvalue. (, cv-qualit) , ( ) (13.3.1.2, 13.6), , . , .

, - prvalue! . prvalue lvalue?

6 Lvalue-to-rvalue (4.1), (4.2) (4.3). :

  • ; . ( ), prvalue , .

, , . , , lvalue , , .

lvalue const std::string , lvalue, prvalue.

+4

GLIBCs. :

#include <string>
#include <iostream>

int main(int argc, char* argv[]) {
    const std::string message("hello world");
    std::cout << std::hex << (void*)&message << std::endl;
    const std::string& toPrint = (argc > 0) ? message : "";
    std::cout << std::hex << (void*)&toPrint << std::endl;
    return 0;
}

( , , ), .

( , ). , . ( , " " ​​, , ).

+6

Source: https://habr.com/ru/post/1624233/


All Articles