在我的C++项目中,我在更换所有内容之前迈出了一步char*,std::string但我发现某个特定场合std::string失败了.
想象一下,我有这两个功能:
void foo1(const std::string& s)
{
...
}
void foo2(const char* s)
{
...
}
Run Code Online (Sandbox Code Playgroud)
如果我写这样的东西:
const char* SL = "Hello to all!";
foo1(SL); // calls malloc, memcpy, free
foo2(SL);
Run Code Online (Sandbox Code Playgroud)
在foo1所述SL将隐式转换成std::string.这意味着std::string构造函数将分配内存,并将字符串文字复制到该缓冲区.在foo2虽然没有所有这些都不会发生.
在大多数实现std::string中应该是超级优化的(例如Copy On Write)但是当我用const char*它构造它时它不是.我的问题是:为什么会这样?我错过了什么吗?我的标准库是不是足够优化还是出于某种原因(我不知道)这是完全不安全的?
最近,当我的类具有只接受一个参数的模板构造函数时,我遇到了一种奇怪的行为.在某些情况下,该课程根本无法初始化.
#include <iostream>
struct Foo
{
template<typename T>
Foo(const T& x)
{
std::cout << "--" << x << std::endl;
}
};
int main(int, char**)
{
Foo f(std::string());
std::cout << "++" << f << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我所拥有的是一个带有你看到的构造函数的Foo结构.在main中,我创建了一个带有空std :: string的新Foo实例.示例编译并输出为:
++1
Run Code Online (Sandbox Code Playgroud)
跆拳道??? 您可能已经注意到这有三个问题.首先,构造函数从未被调用,其次f被打印为"1",第三,没有重载的运算符<<使用cout打印Foo,尽管编译器从不抱怨.这意味着f不是一种Foo.
我略微改变了这个例子:
int main(int, char**)
{
Foo f(std::string(""));
std::cout << "++" << f << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
...并且编译器抛出一个错误,即没有重载的运算符<<并且这是正常的.
int main(int, char**)
{
Foo f(std::string("Hello"));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在的输出是:
--Hello
Run Code Online (Sandbox Code Playgroud)
那是正常的.
问题是当向Foo :: Foo传递一个空对象时,无论是std :: string()还是float()或any_type().我在GCC …