以下代码打印一,二,三.对于所有C++编译器来说,这是否合乎需要?
class Foo
{
const char* m_name;
public:
Foo(const char* name) : m_name(name) {}
~Foo() { printf("%s\n", m_name); }
};
void main()
{
Foo foo("three");
Foo("one"); // un-named object
printf("two\n");
}
Run Code Online (Sandbox Code Playgroud) 假设你有一个全局的类(例如可用于应用程序的运行时)
class MyClass {
protected:
std::string m_Value;
public:
MyClass () : m_Value("hello") {}
std::string value() { return m_Value; }
};
MyClass v1;
Run Code Online (Sandbox Code Playgroud)
当我这样做时,使用第一种形式给了我奇怪的行为
printf("value: %s\n", v1.value().c_str());
Run Code Online (Sandbox Code Playgroud)
看起来字符串在printf可以使用之前从内存中消失了.有时它打印值:hello其他时候它崩溃或什么都不打印.
如果我第一次复制字符串就像这样
std::string copiedString = v1.value();
printf("value: %s\n", copiedString.c_str());
Run Code Online (Sandbox Code Playgroud)
事情确实有效.
当然必须有一种方法可以避免使用临时字符串.
编辑:所以共识是使用const std :: string和返回值.
我知道每个人都说原始代码应该没问题,但我可以告诉你,我在Windows CE上看到MSVC 2005遇到了麻烦,但只能在CE盒子上.不是Win32交叉编译.
关于临时对象何时被销毁,这是否有效:
FILE *f = fopen (std::string ("my_path").c_str (), "r");
Run Code Online (Sandbox Code Playgroud)
在评估调用fopen之后或之后的第一个参数后,是否会立即销毁临时值fopen.
使用以下代码进行测试:
#include <cstdio>
using namespace std;
struct A {
~A() { printf ("~A\n"); }
const char *c_str () { return "c_str"; }
};
void foo (const char *s) { printf ("%s\n", s); }
int main () {
foo (A().c_str());
printf ("after\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
得到:
c_str
~A
after
Run Code Online (Sandbox Code Playgroud)
这表示首先评估整个语句,然后销毁任何临时语句.这种排序是由标准还是特定于实现的强制要求?
我有一个定义如下的方法:
const std::string returnStringMethod()
{
std::string myString;
// populate myString
return myString;
}
Run Code Online (Sandbox Code Playgroud)
现在,在调用者中,我做了类似这样的事情:
const char * ptr = returnStringMethod().c_str();
Run Code Online (Sandbox Code Playgroud)
正如我所看到的,这是返回一些我没想到的截断字符串.但是,以下工作正常:
std::string str = returnStringMethod();
const char * ptr = str.c_str();
Run Code Online (Sandbox Code Playgroud)
有人可以帮我理解这里发生的事情吗?.
PS:我们每周构建一次代码.我上周提交代码时测试了这个,事情还不错.所以,我真的想知道我在这里可能缺少什么.
谢谢,帕万.
我知道为什么以下不起作用,所以我不是在问为什么.但我感觉很糟糕,在我看来,这是一个非常大的编程障碍.
#include <iostream>
#include <string>
using namespace std;
string ss("hello");
const string& fun(const string& s) {
return s;
}
int main(){
const string& s = fun("hello");
cout<<s<<endl;
cout<<fun("hello")<<endl;
}
Run Code Online (Sandbox Code Playgroud)
第一个cout不起作用.第二个cout会.
我关注的是:
是不是可以想象一个方法实现者想要返回一个const引用并且不可避免的参数的情况?
我认为这是完全可能的.
在这种情况下你会用C++做什么?
谢谢.