views:

362

answers:

7

I'm reviewing a collegue's code, and I see he has several constants defined in the global scope as:

const string& SomeConstant = "This is some constant text";

Personally, this smells bad to me because the reference is referring to what I'm assuming is an "anonymous" object constructed from the given char array.

Syntactically, it's legal (at least in VC++ 7), and it seems to run, but really I'd rather have him remove the & so there's no ambiguity as to what it's doing.

So, is this TRULY safe and legal and I'm obsessing? Does the temp object being constructed have a guaranteed lifetime? I had always assumed anonymous objects used in this manner were destructed after use...


So my question could also be generalized to anonymous object lifetime. Does the standard dictate the lifetime of an anonymous object? Would it have the same lifetime as any other object in that same scope? Or is it only given the lifetime of the expression?


Also, when doing it as a local, it's obviously scoped differently:

class A
{
    string _str;

public:
    A(const string& str) :
        _str(str)
    {
     cout << "Constructing A(" << _str << ")" << endl;
    }

    ~A()
    {
     cout << "Destructing A(" << _str << ")" << endl;
    }
};

void TestFun()
{
    A("Outer");
    cout << "Hi" << endl;
}

Shows:

Constructing A(Outer); Destructing A(Outer); Hi

+8  A: 

It's completely legal. It will not be destructed until the program ends.

EDIT: Yes, it's guaranteed:

"All objects which do not have dynamic storage duration, do not have thread storage duration, and are not local have static storage duration. The storage for these objects shall last for the duration of the program (3.6.2, 3.6.3)."

-- 2008 Working Draft, Standard for Programming Language C++, § 3.7.1 p. 63

As Martin noted, this is not the whole answer. The standard draft further notes (§ 12.2, p. 250-1):

"Temporaries of class type are created in various contexts: binding an rvalue to a reference (8.5.3) [...] Even when the creation of the temporary object is avoided (12.8), all the semantic restrictions shall be respected as if the temporary object had been created. [...] Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. [...] There are two contexts in which temporaries are destroyed at a different point than the end of the full-expression. [...] The second context is when a reference is bound to a temporary. The temporary to which the reference is bound or the temporary that is the complete object of a subobject to which the reference is bound persists for the lifetime of the reference except as specified below."

I tested in g++ if that makes you feel any better. ;)

Matthew Flaschen
Is that guaranteed though? I know that it behaves that way in Visual C++, but I want to make sure that according to C++ standard an anonymous object created in that way lives for the lifetime of the program.
Jim
so i guess my real question is, from a C++ standard point of view, do anonymous objects created in a scope (global, etc) also get the same scope, or do anonymous objects only live for the expression in which they're used?
Jim
but it is anonymous, isn't it? Because it's a refernece, not an object.If it were const string SomeConstant = "blah blah blah";then it's an object initialization, but if it is:const stringisn't that instead:const stringIt seems with the reference there there's an anonymous object in between because the const char * can't be assigned to the string reference, only to a string (through conversion to a string).
Jim
but thx for the standard link. I'll look at that. Not trying to pick nits, just want to understand exactly what is happening there and why.
Jim
Martin York
Roddy
Roddy, the OP is not asking about compiler bugs (yes, we all know they're numerous). He's asking what the standard provides for.
Matthew Flaschen
Martin, I've added the section about the rvalue temporary persisting due to the reference.
Matthew Flaschen
David Rodríguez - dribeas
Not directly related to this, but there was a bug in old versions of gcc when temporaries were bound to local statics (http://gcc.gnu.org/bugzilla/show_bug.cgi?id=20416). Personally, although this is legal, I tend to agree that it's not really good style. It also probably takes up more "space" since potentially the implementation of the reference will require storage in addition to the temporary.
Richard Corden
+5  A: 

It might be legal, but still ugly. Leave out the reference !

const string SomeConstant = "This is some constant text";
Magnus Skog
Jim
I wouldn't knock him for it. If it works, I'd leave it be. I think your time would be better spent looking at his design instead.
unforgiven3
I usually do, i just wanted to make sure it was portable. It happens to work on VC++7, but if it was non-standard and they changed it, it could become a liability. If it is, however, standard compliant, I'm fine with it.
Jim
believe me, I don't want to be a code-nazi, but he has done really silly stuff like returning references to local variables from functions before, so I'm trying to make sure this is legal before i let it slide.
Jim
I think the fact that it has caused all this debate should be enough to convince you the code is better off without the reference, even though it is legal. Others seeing it later could have a similar uneasy feeling about it and cause another wave of debate, simply because it's not common.
markh44
agreed! If it's not obvious to a person with a reasonable level of experience, it may be best avoided.
Jim
+2  A: 

It's legal to extend a temporary variable with a const reference, this is used by Alexandrescu's ScopeGaurd see this excellent explanation by Herb Sutter called A candidate for the "Most important const".

That being said this specific case is an abuse of this feature of C++ and the reference should be removed leaving a plain const string.

Motti
+4  A: 

It's as legal as it's ugly.

Gab Royer
+7  A: 

Yes it is valid and legal.

const string& SomeConstant = "This is some constant text";

// Is equivalent too:

const string& SomeConstant = std::string("This is some constant text");

Thus you are creating a temporary object.
This temporary object is bound to a const& and thus has its lifetime extended to the lifespan of the variable it is bound too (ie longer than the expression in which it was created).

This is guranteed by the standard.

Note:

Though it is legal. I would not use it. The easist solution would be to convert it into a const std::string.

Usage:

In this situation because the variable is in global scope it is valid for the full length of the program. So it can be used as soon as execution enters main() and should not be accessed after executiuon exits main().

Though it technically may be avilable before this your usage of it in constructors/destructors of global objects should be tempered with the known problem of global variable initialization order.

Extra Thoughts:

This on the other hand will not suffer from the problem:

char const* SomeConstant = "This is some constant text";

And can be used at any point. Just a thought.

Martin York
Very true, very true. I typically use const char * const unless I have a need to use the heavier string or if i want to use boost or std string fxns against it.
Jim
A: 

By declaring it as const (which means it can't be changed) and then making it a reference, which implies that someone might change it, seems like bad form, at the very least. Plus, as I am sure you understand, global variables are BAD, and rarely necessary.

xcramps
it's not a global variable, it's a global identifier (const). But that's picking nits.
Jim
A: 

Okay, folks correct me if I'm off the deep end, but here's my conclusions listening to all of your excellent responses:

A) it is syntactically and logically legal, the & extends the lifetime of the temp/anonymous from beyond expression level to the life of the reference. I verified this in VC++7 with:

class A { 
    public: A() { cout << "constructing A" << endl; }
    public: ~A() { cout << "destructing A" << endl; }
};

void Foo()
{
    A();
    cout << "Foo" << endl;
}

void Bar()
{
    const A& someA = A();
    cout << "Bar" << endl;
}

int main()
{
    Foo();    // outputs constructing A, destructing A, Foo
    Bar();    // outputs constructing A, Bar, destructing A
    return 0;
}

B) Though it is legal, it can lead to some confusion as to the actual lifetime and the reference in these cases give you no benefit of declaring it as a non-reference, thus the reference should probably be avoided and may even be extra space. Since there's no benefit to it, it's unnecessary obfuscation.

Thanks for all the answers it was a very interesting dicussion. So the long and short of it: Yes, it's syntactically legal, no it's not technically dangerous as the lifetime is extended, but it adds nothing and may add cost and confusion, so why bother.

Sound right?

Jim
Yes, you've got a handle on it now. It's legal, safe, and probably not deliberate obfuscation. But you're right there's no need for the ref. Also, there were some minor errors in this post's code, so I edited it.
Matthew Flaschen
thanks for the edits, i was typing in a shortened version of the code to keep it brief :-)
Jim