Why can't I initialize an object including it in its initial value in C ++?

I debugged the program when I came across the following code, which I mistakenly printed, as shown below:

//Original (wrong)
std::string first("Hello");
std::string second = first + second;

//Instead of this (correct)
std::string first("Hello");
std::string second = first + something_else;

Obviously, I did not try to do this (I can’t think why anyone would like to do this), but it made me think. This is not like the original should work, and I would suggest that it is undefined. Indeed, this was the cause of my problem.

To make the problem more general, consider the following:

SomeType a;
SomeType b = a + b;

Is the behavior undefined simply because it bis not yet initialized (see this answer )?

If the behavior is undefined, then my real question is: why?

undefined , std::string, undefined ( STL, , POD, )?

?

, ++ 11, .

+3
3

++ 11 :

3.3.2 [basic.scope.pdecl]

( 8) ( ), . [:

int x = 12;
{ int x = x; }

x () . - ]

++.

, , .

+6

undefined.

:

[dcl.init]

.......

, ; , .

+1

: - . , , - infact, copy construction; .

SomeType b = a + b;

SomeType b(a + b /*wat?*/);

Part of the motivation for this is RVO. Consider instead the case

SomeType a, b;
SomeType c = a + b;

ccan actually be redirected as an object tempthat is used a.operator+(b)to construct the return value.

SomeType SomeType::operator+(const SomeType& rhs) const
{
    SomeType temp(*this); // RVO will employ `c` here instead of a 4th object.
    ...
    return temp; // yeah, let not and say we did.
}

Please note that you can choose your address:

inptr_t i = (intptr_t)&i;
void* ptr = &ptr;

http://ideone.com/GUJyio

0
source

All Articles