std::string复制构造函数在GCC 4.1.2中不深入
std::string copy constructor NOT deep in GCC 4.1.2?
我想知道我是否误解了一些东西:从std::string
的复制构造函数不复制其内容?
string str1 = "Hello World";
string str2(str1);
if(str1.c_str() == str2.c_str()) // Same pointers!
printf ("You will get into the IPC hell very soon!!");
这会打印"You will get into the IPC hell very soon!!",这让我很恼火。
这是std::string
的正常行为吗?我在某处读到它通常做深度拷贝。
然而,这是预期的工作:
string str3(str1.c_str());
if(str1.c_str() == str3.c_str()) // Different pointers!
printf ("You will get into the IPC hell very soon!!");
else
printf ("You are safe! This time!");
将内容复制到新字符串中
您的string
实现完全有可能使用写时复制,这将解释该行为。尽管这在较新的实现(以及c++ 11实现的不一致性)中不太可能发生。
标准对c_str
返回的指针的值没有限制(除了它指向一个以null结尾的c-string),所以您的代码本质上是不可移植的。
std::string
在编译器中的实现必须是引用计数的。更改其中一个字符串,然后再次检查指针-它们将不同。
string str1 = "Hello World";
string str2(str1);
if(str1.c_str() == str2.c_str()) // Same pointers!
printf ("You will get into the IPC hell very soon!!");
str2.replace(' ',',');
// Check again here.
这是3篇关于参考计数字符串的优秀文章。
http://www.gotw.ca/gotw/043.htm http://www.gotw.ca/gotw/044.htm http://www.gotw.ca/gotw/045.htm相关文章:
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- CRTP 中的复制赋值运算符 - gcc vs clang 和 msvc
- 不可复制类数据成员的统一初始化导致gcc错误
- 防止gcc破坏我的AVX2内部复制到REP MOVS
- 为什么 std::map emplace 需要在 gcc 上有一个复制构造函数
- Gcc 使用 memcpy 作为隐式复制赋值运算符,而不是成员复制
- 为什么 GCC 拒绝复制赋值操作中的常量引用
- 当局部变量被复制到全局变量时,C++GCC优化速度会减慢
- 为什么根据 C++11 标准,std::seed_seq是不可复制的,为什么 gcc/clang 不符合?
- gcc 的 std::bind 在源中的哪个位置将参数复制到数据结构中?
- Clang和GCC与MSVC和ICC的比较:如果复制/移动省略也适用,那么在复制/移动构造函数中是否需要静态断言
- GCC 4.8.1 中的C++11:复制构造函数的列表初始化不起作用
- 如何将一个 ostringstream 对象复制到另一个对象中(使用 gcc-4.7.0)
- 复制构造函数与pch中的const成员函数冲突?一个gcc错误
- clang与gcc运行时的区别:用clang构建的c++类模板在没有复制构造函数的情况下崩溃,用复制构造函数构建的gcc
- 这个不可复制的地图是合法的c++11吗?GCC 4.7和MSVS 2010允许.Clang 3.1不允许
- std::string复制构造函数在GCC 4.1.2中不深入
- 在新版本的 gcc 上返回隐式不可复制结构的 std::map 时出现编译错误
- 编译器的区别:扩展x3::变体需要用gcc定义复制构造函数、复制赋值运算符和默认构造函数,但不需要clang
- 在GCC和Clang下,带有lambda的简单RAII包装器的复制初始化意外失败