以下是未定义的行为吗?
以下是内联(在头文件内定义)静态成员函数。文字字符串“MyClass”是否始终保证位于静态内存中?如果不是,这不会返回堆栈中的指针吗?
const char * className()
{
return "MyClass";
}
编辑:
这个怎么样?
const RWCString& className()
{
return "MyClass";
}
RWCString 是一个字符串类,它有一个采用 const char* 的隐式构造函数。 http://www.roguewave.com /portals/0/products/sourcepro/docs/11/html/toolsref/rwcstring.html
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";
}
Edit:
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个例子:
很好。
"MyClass"
是char const[8]
类型的文字,其生命周期在调用代码之前开始,在代码完成后结束,因此没有问题。然而,第二个例子将不起作用。
它需要在函数内构造
RWCString
类型的对象,以便能够返回对其的引用。但是,在函数中构建为局部变量或临时变量的内容不能通过引用返回,因此您会得到未定义的行为(如果可以编译)。不过,您可以非常简单地将其变成一个“好”函数:
这里我创建一个本地静态对象
N
,它将在第一次调用该函数时构造。因为它是静态的,所以它的生命周期会延伸到调用之后,所以返回它的引用就可以了。编辑:正如史蒂夫指出的那样,临时变量在这里比局部变量更合适。
The first example:
is fine.
"MyClass"
is a literal of typechar 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.
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:
Here I create a local static object
N
which will be constructed the first time the function is called. Because it isstatic
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.
没有。这是完全定义的。该字符串不在堆栈上。它在全局内存中。所以它返回的指针是有效的。 (更好的是:你声明了它
const
)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
)