开发者

Is the following undefined behaviour?

开发者 https://www.devze.com 2023-04-11 03:35 出处:网络
The following is an in-lined(defined inside header file) static member function. Is the literal string \"MyClass\" always guaranteed to be in static memory? If not, will this not be returning a pointe

The following is an in-lined(defined inside header file) static member function. Is the literal string "MyClass" always guaranteed to be in static memory? If not, will this not be returning a pointer in stack?

const char * className()
{
return "MyClass";
}

Ed开发者_如何转开发it:

How about this?

const RWCString& className()
{
return "MyClass";
}

RWCString is an string class which has a implicit constructor which takes a const char*. http://www.roguewave.com/portals/0/products/sourcepro/docs/11/html/toolsref/rwcstring.html


The first example:

const char * className()
{
  return "MyClass";
}

is fine. "MyClass" is a literal of type char const[8] which lifetime begins before your code is invoked and ends after your code is done, so no issue.

The second example, however, will not work.

const RWCString& className()
{
  return "MyClass";
}

It requires and object of type RWCString to be constructed within the function in order to be able to return a reference to it. However what is built as a local variable or temporary within a function cannot be returned by reference, so you get undefined behavior (if it compiles).

You can very simply turn it into a "good" function though:

const RWCString& className()
{
  static RWCString const N = "MyClass";
  return N;
}

Here I create a local static object N which will be constructed the first time the function is called. Because it is static its lifetime extends past the call so it is fine to return a reference to it.

EDIT: as Steve pointed out, temporary is more appropriate that local variable here.


Nope. This is completely defined. The string isn't on the stack. It's in global memory. So the pointer it returns is valid. (even better: you declared it const)

0

精彩评论

暂无评论...
验证码 换一张
取 消